如何在 package.json 文件中不设置 "type": "module" 的情况下导入 esm 库?

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

我有一个运行良好的打字稿节点项目。现在我正在尝试将 vinejs 库添加到项目中。但 VineJS 是一个仅 ESM 的包,当将其添加到项目并尝试运行 ts-node 时,会出现以下错误:

Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

然后我在脚本中的 ts-node 命令中向 package.json 添加了“type”:“module”和“--esm”。此时我可以毫无错误地运行 ts-node。

但是后来我尝试构建项目并通过 ./dist 文件夹中构建中生成的 index.js 文件运行它,并收到另一个错误。

ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'C:\dev\personal\test\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

如何通过 package.json 中定义的 "type": "module" 通过 dist 文件夹运行项目?

我的配置文件。

package.json

{
  "name": "test",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "start:dev": "ts-node --esm -r tsconfig-paths/register src/index.ts",
    "start:dev-watch": "nodemon --watch src/** --ignore src/**/*.spec.ts --exec npm run start:dev",
    "build": "tsc && tsc-alias",
    "start:prod": "node dist/index.js",
  },
  "license": "ISC",
  "dependencies": {
    "@vinejs/vine": "^1.5.2",
    "express": "^4.18.2"
  },
  "devDependencies": {
    "@types/express": "^4.17.17",
    "@types/node": "^20.3.3",
    "nodemon": "^3.0.1",
    "ts-node": "^10.9.1",
    "tsc-alias": "^1.8.7",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^5.1.6"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "rootDir": "./src",
    "moduleResolution": "Node",
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    },
    "allowImportingTsExtensions": true,
    "outDir": "./dist",
    "noEmit": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
  }
}

预计导入仅 ESM 包并通过 dist 文件夹中生成的文件运行节点项目。

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

最简单的方法是设置

"type": "module"
并使用
const pkg = await import('vinejs')
导入“VineJS”,这就是commonJS项目如何导入仅限ESM的项目。

如果您选择完全转换为 ESM,则需要对配置和源进行大量更改,其中之一是确保每个本地导入都具有

.js
扩展名并停止使用
exports 
。您可以在网上找到完整的迁移指南,但我认为将所有内容写下来有点超出了堆栈溢出答案的范围。

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