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

标签 javascript node.js typescript eslint

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

关于javascript - 如果没有 .js 扩展名,则为 ERR_MODULE_NOT_FOUND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67010910/

相关文章:

javascript - 谷歌钱包错误 : The frame requesting access has a protocol of "https", 正在访问的框架具有 "http"的协议(protocol)

javascript - https 转 http 请求

javascript - 在过渡期间更新变换会导致过渡在 IE 和 MS 边缘上闪烁

node.js - 如何在node.js中监听192.168.1.1/subdir/?

javascript - 设置状态时这段代码是什么意思?

typescript - 如何覆盖通过@types/package 安装的不正确的 TypeScript 类型定义

javascript - jQuery 搜索元素中的文本作为 SQL 查询 LIKE?

javascript - 在一个函数/方法上使用 'strictNullChecks' 注释

node.js - 页面重新加载 Node Js和Socket.io时获取socket.id

typescript - TsLint 说 "expected callSignature to have a typedef."是什么意思