自 Node 13.10 起,有另一种选择,最具前瞻性的选择是:
在您想使用的 CommonJS 库的存储库中提交问题,
说服维护者 发布
双重包(ESM + CommonJS),使用
条件导出。
对于使用 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"
},
}
会手动重命名输出,因为
TypeScript目前无法直接生成.mjs
输出,而
--outFile
与ES模块不兼容。
exports
块有“
条件导出”,使得使用ES模块转译的TypeScript代码可以使用命名导入。
TypeScript不直接支持.mjs输入文件。
对于这个简单的模块,不需要
tsconfig.json
。