javascript typescript不替换tsconfig中定义的非相对路径

nlejzf6q  于 2023-03-06  发布在  Java
关注(0)|答案(3)|浏览(144)

我尝试使用自定义路径来简化常用模块的导入,并设置了以下配置:

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": false,
        "removeComments": true,
        "preserveConstEnums": true,
        "outDir": "build",
        "allowJs": true,
        "target": "es5",
        "sourceMap": true,
        "baseUrl": ".",
        "paths": {
            "config": ["app/config"]
        }

    },
    "exclude": [
        "node_modules”,
        "build"
    ]
}

我试图使用“config”导入config模块,但应用程序在要求配置文件时失败。编译文件内的要求路径仍然是“config”。

// result:
var config = require("config");
// what is should be:
var config = require("../../config");

即使模块解决日志显示问题已得到解决。

======== Resolving module 'config' from '/abs/path/routes/internal/signin/index.ts'. ========
Module resolution kind is not specified, using 'NodeJs'.
'baseUrl' option is set to '/abs/path', using this value to resolve non-relative module name 'config'
'paths' option is specified, looking for a pattern to match module name 'config'.
Module name 'config', matched pattern 'config'.
Trying substitution 'config', candidate module location: 'config'.
Loading module as file / folder, candidate module location '/abs/path/config', target file type 'TypeScript'.
File '/abs/path/config.ts' does not exist.
File '/abs/path/config.tsx' does not exist.
File '/abs/path/config.d.ts' does not exist.
File '/abs/path/config/package.json' does not exist.
File '/abs/path/config/index.ts' exist - use it as a name resolution result.
======== Module name 'config' was successfully resolved to '/abs/path/config/index.ts'. ========

在编译后修改路径以指向正确的模块时,我遗漏了什么?

v64noz0r

v64noz0r1#

显然paths从来没有打算把url解析成它的相对版本,你应该使用某种后处理器来做这件事,我用的是this Babel plugin

1qczuiv0

1qczuiv02#

可以使用以下代码修复非相对导入:obs:安装ts配置路径和ts节点

"scripts": {
"start": "node -r tsconfig-paths/register -r ts-node/register ./dist/app.js",
}
wrrgggsh

wrrgggsh3#

由绑定来执行此操作,另请参见**tsconfig-replace-paths**。它确实会替换引用。
例如

"scripts": {
  "build": "tsc --project tsconfig.json 
            && tsconfig-replace-paths --project tsconfig.json",
}

但是,您仍然会遇到绑定问题。请参见https://github.com/microsoft/TypeScript/issues/26565

相关问题