要导出到 TypeScript 中的 CommonJS 和 ES 模块,请在导出中设置默认属性:
myModule.default = myModule; export = myModule; 借助 Bun,使用 CommonJS 加载 Babel 的速度大约比使用 ES 模块快 2.4 倍。 CommonJS 并不是过去时代的遗物,Bun 今天将其视为一等公民。

npm 上有关 ESM 的最新信息:ESM 现在为 9%,dual 为 3.8,faux ESM 为 13.7%,CJS 为 73.6%。此数据仅包括最流行的 npm 软件包(每周超过 100 万次下载和/或 500 多个其他软件包依赖于它),不包括 TypeScript types /* 软件包。

全局安装 typescript(如果尚未安装):
$ npm install --global typescript 给定函数 myModule:
// index.ts const myModule = () => {}; 在 CommonJS 中导出默认值:
// index.ts // ... export = myModule; 通过运行 tsc index.ts 验证输出:
// index.js 'use strict'; var myModule = function() {}; module.exports = myModule; 这意味着你可以使用 CommonJS 来要求:
const myModule = require('./index'); 但是用 ES Modules 导入会报错:
error TS1259: Module '"index"' can only be default-imported using the 'esModuleInterop' flag 1 import myModule from './index'; ~~~~~~~~ index.ts:3:1 3 export = myModule; ~~~~~~~~~~~~~~~~~~ This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. Found 1 error. 要导出 ES 模块中的默认值:
// index.ts // ... export default myModule; 通过运行 tsc index.ts 验证输出:
// index.js 'use strict'; exports.__esModule = true; var myModule = function() {}; exports['default'] = myModule; 这意味着您可以使用 ES 模块导入:
import myModule from './index'; 但使用 CommonJS 要求意味着您需要使用默认属性:
const myModule = require('./index').default; 如果您尝试导出 CommonJS 和 ES 模块:
// index.ts // ... export = myModule; export default myModule; 你会得到这样的错误:
tsc index.ts index.ts:3:1 - error TS2309: An export assignment cannot be used in a module with other exported elements. 3 export = myModule; ~~~~~~~~~~~~~~~~~~ Found 1 error. 那么我们如何实现互操作性呢?我们可以复制 Babel 的方法并在主导出对象上设置默认属性:
// index.ts // ... myModule.default = myModule; export = myModule; 这适用于 myModule,因为函数是 JavaScript 中对象的实例。
因此,您可以使用 CommonJS 和 ES 模块语法导入:
// CommonJS const myModule = require('./index'); // ES Modules import myModule from './index';