Typescript tsconfig.json的baseUrl不工作

Typescript tsconfig.json的baseUrl不工作,typescript,tsconfig,Typescript,Tsconfig,我的项目结构是 src/ 客户/ 模块/ 服务器/ app.ts 我在app.ts文件中使用非相对导入导入模块 import * as DB from '@modules/DB'; 因为我不想使用来自“./modules/DB”的 我的tsconfig.json是 { "compileOnSave": true, "compilerOptions": { "module": "commonjs", "target": "ES6", "noImplicitAny": t

我的项目结构是 src/ 客户/ 模块/ 服务器/ app.ts


我在app.ts文件中使用非相对导入导入模块

import * as DB from '@modules/DB';
因为我不想使用来自“./modules/DB”的

我的tsconfig.json是

{
"compileOnSave": true,
"compilerOptions": {
    "module": "commonjs",
    "target": "ES6",
    "noImplicitAny": true,
    "sourceMap": true,
    "preserveConstEnums": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "traceResolution": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "declaration": true,
    "typeRoots": [
        "/"
    ],
    "baseUrl": "./src",
    "paths": {
        "@modules/*": [
            "modules/*"
        ]
    }
},
"exclude": [
    "src/client/"
]
}

当我追踪决议时,得到了这个

======== Module name '@modules/DB' was successfully resolved to '/Users/pengju/projects/pomelo-ts-starter/src/modules/DB/index.ts'. ========
它似乎成功地导入了

但在编译时,vscode仍然会出错

[ts] Cannot find module '@modules/DB'. 
从“@modules/DB”导入*为DB在app.ts中

然后我检查编译的app.js, find
const DB=require(“@modules/DB”)


baseUrl和路径选项无法将“@modules/DB”更改为“./modules/DB”?那么,它们会做什么呢?

这里的问题是TypeScript编译器不会更新JS文件中的路径,JavaScript引擎对TypeScript配置一无所知,您在Tconfig中指定的只是“编译时”使用,当您将TypeScript编译成JS时,您需要执行与TS编译器相同的工作,但要将解析的路径保存在JS文件中

简单地说,需要处理所有JS文件,并用“真实”路径替换别名

人们经常建议WebPack是一个怪物,有一个非常简单的工具叫做tspath,你可以在项目目录中运行它,它会读取你的tsconfig.json并相应地更新JS源文件

安装tspath用于解析ts路径的npm工具注意:tspath需要最新版本的节点

npm install -g tspath
运行TypeScript编译器后,从项目目录运行:

tspath

跳过提示

更多信息请访问:

tspath
tspath -f