我无法在 Node.js 项目中将 ES6 模块与 typescript 一起使用

问题描述 投票:0回答:1

我想在我的 Node.js 项目中同时使用 typescript 和 es6 模块,此外,我希望编译为 javascript 语言的文件具有 es6 模块。

这是我的 package.json :

{
  "name": "arep",
  "version": "1.0.0",
  "description": "",
  "main": "app.ts",
  "type": "module",
  "scripts": {
    "start": "nodemon --exec ts-node app.ts",
    "build": "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.4.1",
    "express": "^4.18.2",
    "mysql2": "^3.9.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.21",
    "@types/node": "^20.11.17",
    "nodemon": "^3.0.3",
    "ts-node": "^10.9.2",
    "typescript": "^5.3.3"
  }
}

这是我的 tscongif.json :

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

这是我得到的错误:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/rznkolds/Desktop/Standart/2- Development/2- Applications/1- NodeJS/arep/app.ts
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
    at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
    at defaultLoad (node:internal/modules/esm/load:141:22)
    at async nextLoad (node:internal/modules/esm/hooks:865:22)
    at async nextLoad (node:internal/modules/esm/hooks:865:22)
    at async Hooks.load (node:internal/modules/esm/hooks:448:20)
    at async handleMessage (node:internal/modules/esm/worker:196:18) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

当我使用 commonjs 模块执行此操作时,一切正常,但是当我使用 es6 模块执行此操作时,出现此错误。 我找不到关于此错误的太多资源。在很多地方,人们通过将其变成 CommonJS 模块来解决问题。

javascript node.js typescript tsconfig ts-node
1个回答
0
投票

您遇到的错误是因为 Node.js 自版本 14.x 起并不原生支持 ES 模块 (ESM)。这意味着当您尝试运行 package.json 中类型设置为“module”的 .ts 文件时,Node.js 将抛出错误,因为它不知道如何处理 .ts 文件。

要解决此问题,您有以下几种选择:

  1. 使用 tsconfig.json 文件中的 esModuleInterop 选项。这会 允许 TypeScript 发出与 CommonJS 兼容的代码 和无害环境管理。但是,如果您想严格执行此操作,这可能并不理想 使用 ESM。

  2. 对 TypeScript 文件使用 .mjs 文件扩展名。这告诉 Node.js 将文件视为 ESM 模块。你需要更新 你的 package.json 指向 .mjs 文件:

    { “名称”:“阿雷普”, “版本”:“1.0.0”, “描述”: ””, "main": "app.mjs", “类型”:“模块”, “脚本”:{ “开始”:“nodemon --exec ts-node app.mjs”, “构建”:“tsc” }, “关键字”:[], “作者”: ””, “许可证”:“ISC”, “依赖项”:{ "dotenv": "^16.4.1", "express": "^4.18.2", “mysql2”:“^3.9.1” }, “开发依赖项”:{ "@types/express": "^4.17.21", "@types/node": "^20.11.17", "nodemon": "^3.0.3", "ts-node": "^10.9.2", “打字稿”:“^5.3.3” } }

  3. 运行 TypeScript 文件时使用 --esModuleInterop 标志 与 ts 节点。这将实现与 tsconfig.json 文件中的 esModuleInterop 选项。

  4. 升级到 Node.js 16.x 或更高版本,该版本具有实验性支持 ES 模块。您可以通过运行来启用此实验性功能 Node.js 带有 --experimental-modules 标志。

就个人而言,我建议使用 .mjs 文件扩展名方法,因为它最符合您在 Node.js 项目中使用 ES 模块的目标。

© www.soinside.com 2019 - 2024. All rights reserved.