在package.json中设置“type”:“module”并从文件夹./dist中的构建文件运行项目

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

我有一个运行良好的打字稿节点项目。现在我正在尝试将 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\prisma_teste_2\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
© www.soinside.com 2019 - 2024. All rights reserved.