【问题标题】:ERR_MODULE_NOT_FOUND if no .js extension如果没有 .js 扩展名,则 ERR_MODULE_NOT_FOUND
【发布时间】:2021-07-04 17:34:09
【问题描述】:

我有一个打字稿项目,当我尝试使用 node 运行我编译的 app.js 文件时,我得到了 ERROR_MODULE_NOT_FOUND 'path/to/compiled/file'。但是,如果我在我的 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 {};

【问题讨论】:

  • 模块所在目录下是否有多个同名文件?您是否将.js 用于打字稿文件中的模块?
  • 感谢您的评论!我已经编辑了我的帖子,包括 app.ts 代码。我没有在我的打字稿文件中使用扩展名。此外,模块中有两个同名的文件:api.js 和 api.js.map,它们都是由编译器创建的。
  • 没有扩展名的问题可能是由于从哪个文件导入不明确,因为它可以从多个文件中导入。我还假设如果将扩展名添加到 ts 文件中,ts 将使用扩展名进行编译
  • 如果我在 typescript 文件中添加 .js 扩展名,我将无法解析路径,如果我删除 api.js.map 文件,它仍然无法工作......
  • stackoverflow.com/questions/55251956/… 回答你的问题了吗?

标签: javascript node.js typescript eslint


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多