将节点从 16 升级到 20 会抛出 ERR_REQUIRE_ESM

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

我正在尝试从版本 16 => 20 升级节点
我还决定尝试完全升级其他一些库
我尝试在升级后启动我的后端

% yarn run dev
[nodemon] 3.0.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `DB_NAME=menzei_app ts-node --transpileOnly --files src/index.ts`

不久之后

/Users/.../backend/node_modules/ts-node/dist/index.js:851
            return old(m, filename);
                   ^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/.../backend/node_modules/file-type/index.js from /Users/.../backend/src/feature-core/upload-file.ts not supported.
Instead change the require of index.js in /Users/.../backend/src/feature-core/upload-file.ts to a dynamic import() which is available in all CommonJS modules.
    at require.extensions.<computed> [as .js] (/Users/.../backend/node_modules/ts-node/dist/index.js:851:20)

我无法理解此错误的根本原因,但我觉得这可能与升级后未修复的 tsconfig 文件有关?
tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "./src",
    "paths": {
      "~/*": ["./*"]
    }
  },
  "include": ["src", "../backend/src/@types"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

tsconfig.node.json

{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}

我不确定需要更新什么或如何更新,我尝试根据一些 github 问题进行一些更改,但找不到解决方案。

node.js reactjs typescript tsconfig
1个回答
0
投票

发生此错误是因为您正在导入的包已转换为仅限 ESM 的包(ECMAScript 模块),这意味着无法再使用 require() 导入该包。所以正如你所说,你首先升级了一些库,你必须检查它们是否不再支持 ESM 。

要解决此错误,请使用 imports/exports 而不是 require() .

不要忘记将

"type": "module"
添加到您的 package.json 文件中:.

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