从Node 13.10开始,还有一个选择,最有前瞻性的一个:
在您想要使用的 CommonJS 库的 repo 中提交问题,persuading the maintainers 以发布 dual packages (ESM + CommonJS),使用 conditional exports。
对于用 TypeScript 编写的库,生成双包很容易,不需要 Babel 或 rollup 或任何其他工具。这是我在local-iso-dt 中的做法:
package.json的相关部分:
{
"name": "local-iso-dt",
"version": "3.1.0",
"description": "...",
"type": "commonjs",
"exports": {
"node": {
"import": "./index.mjs",
"require": "./index.js"
},
"default": "./index.mjs"
},
"main": "index.js",
"files": [
"index.ts",
"index.mjs",
"index.js"
],
"scripts": {
"clean": "rm index*.js index.mjs",
"prepublishOnly:cjs": "tsc index.ts --esModuleInterop --removeComments",
"prepublishOnly:esm": "tsc index.ts -t ES2015 --types node && mv index.js index.mjs",
"prepublishOnly": "npm run prepublishOnly:esm; npm run prepublishOnly:cjs"
},
"devDependencies": {
"typescript": "^4.0.2"
},
}
prepublishOnly:esm 手动重命名输出,因为 TypeScript can't yet generate .mjs output directly 和 --outFile 不适用于 ES 模块。
exports 块具有“conditional exports”,它启用使用 ES 模块转译的 TypeScript 代码,以使用命名导入。TypeScript doesn't directly support .mjs input files。
这个简单的模块不需要tsconfig.json。