首页 > 解决方案 > 如果没有 .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 {};

标签: javascriptnode.jstypescripteslint

解决方案


尝试在节点上设置新的打字稿项目时,我遇到了完全相同的问题。

最后为我解决的问题是在模块选项上用 commonjs 替换 esnext。

我以前使用 esnext 是因为它有一个顶级的 await,但是通过使用 async 函数包装 await 来解决这个问题。

我无法解释为什么使用 esnext 编译的 javascript 导入没有 .js 扩展名,或者如何调整编译器为也将被编译的本地模块添加此扩展名。


推荐阅读