而不是相对模块导入我想导入我的模块,如下所示: import { IntHelper } from 'utils/IntHelper';
. 尽管intellisense在VSCode中工作正常,但已转换的javascript文件会抛出异常: Cannot find module
.
My project structure:
根
-
dist
-
src
-
MyProject.ts
-
utils
-
IntHelper.ts
-
tsconfig.json
File: MyProject.ts
import { IntHelper } from 'utils/IntHelper';
File: IntHelper.ts
export module IntHelper {
export const xy: string = 'Test';
export function crossSum(int: number) {
return int; // Nonsense - ofcourse.
}
}
Tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"*",
"src/*"
]
}
}
}
My question:
为什么它会在javascript文件中抛出无法找到模块异常,即使它在打字稿文件中看起来很好?当我将 'utils/IntHelper'
部分悬停在打字稿文件的导入行中时,VSCode也会显示该模块的正确路径 .
2 回答
您遇到的问题与许多其他问题相同,相信TypeScript编译器实际上会将已解析的路径保存到JS文件中,但实际情况并非如此,您需要自己解决这个问题,或者使用WebPack工具通常是人们的建议,但WebPack是一个怪物,请看这个答案:
Typescript2 path module resolution
这很可能也会解决您的问题!
当然,在您的情况下,节点会对模块感到困惑,因为它期望所有非相对路径都存在于node_modules中 . 打字稿的好方法是使用tsconfig的
paths
部分,如下所示:现在我们可以
但我们仍然需要通知webpack或节点有关路径配置的信息: