编译后 Typescript 模块未找到错误

Bug*_*eeb 19 typescript

这让我发疯。如何让打字稿正确编译导入的模块?我的 main.ts 也是import { AddListeners } from './listeners';一个 .ts 文件,export function AddListeners()但是当编译为 main.js 时,这一行不会改变,节点会抛出此错误:

错误 [ERR_MODULE_NOT_FOUND]:找不到从 C:\Users\bugbe\Documents\VSCode\tricorder\dist\main.js 导入的模块“C:\Users\bugbe\Documents\VSCode\tricorder\dist\listeners”

这是我的 tsconfig.json:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "outDir": "dist",
    "module": "es2020",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2020",
    "typeRoots": [
      "node_modules/@types"
    ],
    "baseUrl": "./",
    "paths": {
      "*":[
        "node_modules/"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

因此导入模块的代码无法正确编译,因为要工作它应该看起来像import { AddListeners } from './listeners.js';

Jos*_*ole 18

我在使用 Node 15 将 TS 编译为 ES 模块时遇到了这个问题。事实证明,TS 在编译模块时不会自动将“.js”扩展名添加到导入路径中,但 ES 路径解析算法期望存在该扩展名。

对我来说,这就像使用--es-module-specifier-resolution=node标志让 Node 使用旧的require()解析行为一样简单:

node --es-module-specifier-resolution=node ./dist/src/main
Run Code Online (Sandbox Code Playgroud)

作为参考,我的设置如下:

包.json

{
    ...
    "type": "module"
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
    "include": ["src/**/*", "package.json"],
    "compilerOptions": {
        "composite": true,
        "declaration": true,
        "declarationMap": true,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "importHelpers": true,
        "module": "ESNext",
        "moduleResolution": "node",
        "newLine": "LF",
        "noFallthroughCasesInSwitch": true,
        "noImplicitReturns": true,
        "noUncheckedIndexedAccess": true,
        "noUnusedLocals": false,
        "noUnusedParameters": false,
        "preserveConstEnums": true,
        "removeComments": true,
        "resolveJsonModule": true,
        "strict": true,
        "target": "ES2018"
    }
}
Run Code Online (Sandbox Code Playgroud)


Han*_*din 7

您应该使用该标志通过节点运行程序,--es-module-specifier-resolution=node因为您使用的是 es6+ 模块类型。如果您使用 CommonJS,则不会遇到此问题。


shy*_*hiy 1

  1. 在 tsconfig.json 中有“module”:“es2020”。这意味着 typescript 将编译您的代码以使用 ES 模块。要使用 ES 模块运行 Nodejs,您需要 Nodejs v12 并使用该--experimental-modules标志运行它,或者使用 NodeJS 版本 13.2.0+ 来不使用该--experimental-modules标志运行。
  2. 如果您无法使用较新版本的 Nodejs,则需要更改"module": "es2020""module": "CommonJS".