这似乎是一个微不足道的问题,但需要使用什么设置/配置来解决这个问题并不十分明显。
下面是 Hello World 程序的目录结构和源代码:
目录结构:
| -- HelloWorldProgram
| -- HelloWorld.ts
| -- index.ts
| -- package.json
| -- tsconfig.json
索引:
import {HelloWorld} from "./HelloWorld";
let world = new HelloWorld();
HelloWorldd.ts:
export class HelloWorld {
constructor(){
console.log("Hello World!");
}
}
Package.json:
{
"type": "module",
"scripts": {
"start": "tsc && node index.js"
}
}
现在,执行命令 tsc && node index.js
会导致以下错误:
internal/modules/run_main.js:54
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'HelloWorld' imported from HelloWorld\index.js
Did you mean to import ../HelloWorld.js?
at finalizeResolution (internal/modules/esm/resolve.js:284:11)
at moduleResolve (internal/modules/esm/resolve.js:662:10)
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:752:11)
at Loader.resolve (internal/modules/esm/loader.js:97:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:242:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:50:40)
at link (internal/modules/esm/module_job.js:49:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
很明显,问题似乎源于这样一个事实: 在 index.ts
类型脚本文件中,import 语句(import {HelloWorld} from "./HelloWorld";
)中没有 .js
扩展名。在编译过程中,类型脚本没有抛出任何错误。但是,在运行时 Node (v14.4.0)需要 .js
扩展。
希望上下文说清楚了。
现在,如何更改编译器输出设置(tsconfig.json 或任何标志) ,以便在 index.js
文件中的 Typecript to Javascript 编译期间,本地相对路径导入(如 import {HelloWorld} from ./Helloworld;
)将被 import {HelloWorld} from ./Helloworld.js;
替换?
注:
It is possible to directly use the .js extension while importing inside typescript file. However, it doesn't help much while working with hundreds of old typescript modules, because then we have to go back and manually add .js extension. Rather than that for us better solution is to batch rename and remove all the .js extension from all the generated .js filenames at last.