使用Typescript报错ERR_REQUIRE_ESM

问题

环境:NodeJs + Typescript + WebStrom
安装了一个依赖包之后,使用过程中,总是报错:

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/xx/WebstormProjects/xx/node_modules/btc-xx/dist/index.js from /Users/xx/WebstormProjects/xx/src/StakeTest.js not supported.
Instead change the require of index.js in /Users/xx/WebstormProjects/xx/src/StakeTest.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/xx/WebstormProjects/xx/src/StakeTest.js:16:26) {
  code: 'ERR_REQUIRE_ESM'
}

瞎分析

大致意思应该是,我所依赖的包,只支持ES,但是我却使用 require 导入,require 只在 commonJs 支持,所以报错了。

我看了下编译后的 js 文件里面确实用的 require,那么问题就是如何让编译后的文件使用 import 了。

package.json

{
  "name": "xx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "xx": "^0.1.1",
    "axios": "^1.3.2"
  },
  "devDependencies": {
    "@types/node": "^20.11.5"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

解决

本着不求甚解和快速解决的精神,在网上找了一些解决方案拼接起来,最后我的措施如下:

  1. 在 package.json 添加 "type": "module" 配置
{
  "name": "xx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "xx": "^0.1.1",
    "axios": "^1.3.2"
  },
  "devDependencies": {
    "@types/node": "^20.11.5"
  },
"type": "module",
}
  1. 在 tsconfig.json 修改和添加配置 "module": "es2016" 、"moduleResolution": "node"
{
  "compilerOptions": {
    "target": "es2016",
    "module": "es2016",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

问题的确是解决了,不过也没办法再用 require 了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容