我有一个 typescript 项目,当我尝试使用 Node 运行已编译的 app.js
文件时,我得到了 ERROR_MODULE_NOT_FOUND 'path/to/compiled/file'
。但是,如果我像这样在我的 app.js 中的导入语句中添加 .js 扩展名,我就会摆脱这个错误 import { function } from "./path/file.js";
怎么做我让 typescript 编译器自动添加这些 .js 扩展名?或者,让 Node 在没有 .js 扩展名的情况下工作?
我的 tsconfig.json
看起来像这样:
{
"compilerOptions": {
"module": "esnext",
"target": "es5",
"noImplicitReturns": true,
"noUnusedLocals": true,
"outDir": "dist",
"sourceMap": true,
"moduleResolution": "node",
"esModuleInterop": true,
"isolatedModules": true,
"resolveJsonModule": true,
"typeRoots": ["./src/types", "node_modules/@types"],
"baseUrl": "./src",
"paths": {
"types": ["types"],
"types/*": ["types/*"],
"@data/*": ["data/*"],
"@execute/*": ["execute/*"],
"@indicators/*": ["indicators/*"],
"@services/*": ["services/*"],
"@strategies/*": ["strategies/*"],
"*": ["node_modules/*"]
}
},
"compileOnSave": true,
"include": ["src", "test", "dist"],
"exlude": ["src/types"]
}
我的 app.ts
看起来像这样:
import { function } from "./path/file";
function();
console.log("test");
export {};
最佳答案
我在尝试在 Node 上设置新的 typescript 项目时遇到了完全相同的问题。
最后为我解决的是在模块选项上用 commonjs 替换 esnext。
我之前使用 esnext 是因为顶层等待,但通过使用异步函数包装等待来解决这个问题。
我无法解释为什么使用 esnext 导入的已编译 javascript 没有 .js 扩展名,或者如何调整编译器以便为也将被编译的本地模块添加此扩展名。
关于javascript - 如果没有 .js 扩展名,则为 ERR_MODULE_NOT_FOUND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67010910/