javascript - 如果没有 .js 扩展名,则为 ERR_MODULE_NOT_FOUND

我有一个 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 扩展名,或者如何调整编译器以便为也将被编译的本地模块添加此扩展名。

https://stackoverflow.com/questions/67010910/

相关文章:

spring-boot - StreamingResponseBodyReturnValueHand

android - 如何在 Android 中更改 TextInputLayout 的 boxStr

java - 在 Spring Cloud Gateway 中获取真实的客户端 IP 地址

python - 类型错误 : forward() takes 2 positional argum

git - 如何使用 gitlab-ci.yml 进行简单的 pull ?

javascript - 如何让 Bootstrap Toasts 不自动消失?

javascript - SwiftUI:在 macOS 上与 WKWebView 的 Javasc

mongodb - 如何在 Rust 中使用 Mongodb::cursor?

validation - VeeValidate 4 : two forms on one page

ios - FaSTLane 设置 - 致命 : could not read Password f