前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TypeScript 导出 CommonJS 和 ES 模块

TypeScript 导出 CommonJS 和 ES 模块

作者头像
小弟调调
发布2023-08-28 14:46:25
4400
发布2023-08-28 14:46:25
举报
文章被收录于专栏:埋名埋名

要导出到 TypeScript 中的 CommonJSES 模块,请在导出中设置默认属性:

代码语言:javascript
复制
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(如果尚未安装):

代码语言:javascript
复制
$ npm install --global typescript 

给定函数 myModule

代码语言:javascript
复制
// index.ts const myModule = () => {}; 

CommonJS

CommonJS 中导出默认值:

代码语言:javascript
复制
// index.ts // ... export = myModule; 

通过运行 tsc index.ts 验证输出:

代码语言:javascript
复制
// index.js 'use strict'; var myModule = function() {}; module.exports = myModule; 

这意味着你可以使用 CommonJS 来要求:

代码语言:javascript
复制
const myModule = require('./index'); 

但是用 ES Modules 导入会报错:

代码语言:javascript
复制
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 Modules

要导出 ES 模块中的默认值:

代码语言:javascript
复制
// index.ts // ... export default myModule; 

通过运行 tsc index.ts 验证输出:

代码语言:javascript
复制
// index.js 'use strict'; exports.__esModule = true; var myModule = function() {}; exports['default'] = myModule; 

这意味着您可以使用 ES 模块导入:

代码语言:javascript
复制
import myModule from './index'; 

但使用 CommonJS 要求意味着您需要使用默认属性:

代码语言:javascript
复制
const myModule = require('./index').default; 

CommonJS + ES Modules

如果您尝试导出 CommonJSES 模块:

代码语言:javascript
复制
// index.ts // ... export = myModule; export default myModule; 

你会得到这样的错误:

代码语言:javascript
复制
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 的方法并在主导出对象上设置默认属性:

代码语言:javascript
复制
// index.ts // ... myModule.default = myModule; export = myModule; 

这适用于 myModule,因为函数是 JavaScript 中对象的实例。

因此,您可以使用 CommonJSES 模块语法导入:

代码语言:javascript
复制
// CommonJS const myModule = require('./index');  // ES Modules import myModule from './index'; 
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-08-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 JSdig 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 先决条件
  • CommonJS
  • ES Modules
  • CommonJS + ES Modules
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档