javascript - 如果没有 .js 扩展名,则 ERR_MODULE_NOT_FOUND
问题描述
我有一个打字稿项目,ERROR_MODULE_NOT_FOUND 'path/to/compiled/file'
当我尝试使用 node.js 运行我的编译app.js
文件时,我得到了这个项目。但是,如果我像这样在我的 app.js 中的 import 语句中添加 .js 扩展名,我会摆脱这个错误import { function } from "./path/file.js";
如何让 typescript 编译器自动添加这些 .js 扩展名?或者,让节点在没有 .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 {};
解决方案
尝试在节点上设置新的打字稿项目时,我遇到了完全相同的问题。
最后为我解决的问题是在模块选项上用 commonjs 替换 esnext。
我以前使用 esnext 是因为它有一个顶级的 await,但是通过使用 async 函数包装 await 来解决这个问题。
我无法解释为什么使用 esnext 编译的 javascript 导入没有 .js 扩展名,或者如何调整编译器为也将被编译的本地模块添加此扩展名。
推荐阅读
- python - 在try中捕获异常后如何继续循环...除了
- android - 当 Firebase 身份验证活动设置 setOnClickListener 时出现 NullPointerException
- java - Apache POI:CellType 比较无法按预期工作
- spring - 弹簧反应器中的rxjs管道方法等效于什么?
- sql-server - 如何在列中显示特定条件?
- javascript - 拦截 XHR 请求,javascript 做出反应
- html - 由于某种原因,图片不会在文章和旁边居中
- ruby-on-rails - 我可以将 Prawn 生成的 PDF 上传到 Cloudinary on Rails 吗?
- python - Word2vec中词类比背后的操作是什么?
- sql - 如何将字段的总和聚合到字符串_聚合值 Postgres