繁体   English   中英

ERR_MODULE_NOT_FOUND 如果没有.js 扩展

[英]ERR_MODULE_NOT_FOUND if no .js extension

我有一个 typescript 项目,当我尝试使用节点运行编译的app.js文件时,我得到了ERROR_MODULE_NOT_FOUND 'path/to/compiled/file' 但是,如果我在我的 app.js 中的 import 语句中添加 a.js 扩展名,就像import { function } from "./path/file.js"; 如何让 typescript 编译器自动添加 these.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 {};

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

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

我以前使用 esnext 是因为有一个顶级等待,但是通过使用异步 function 包装等待来解决这个问题。

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

我有同样的错误。 typescript 项目中的结尾“.js”看起来很奇怪,但是当我尝试这样启动应用程序时,没有它就不起作用:

"start": "node ."

如果您添加--experimental-specifier-resolution=node那么它将起作用。 我不确定向应用程序添加“实验性”内容是否是一种好习惯,但您可以将其用作临时解决方案。

"start": "node --experimental-specifier-resolution=node ."

此外,节点 v18 正在警告您:ExperimentalWarning:

Node.js 说明符分辨率标志是实验性的。 它可以随时更改或删除

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM