Redian新闻
>
为什么 2022 年 ESM 又被发布了一次 ?

为什么 2022 年 ESM 又被发布了一次 ?

科技

这是我最近的一个疑问,明明我们已经用 ESM 写了N年代码了,为啥 2022 年 Node18 和 TS4.7 又宣称自己开始支持 ESM 了?


一个DEMO项目



// src/a.ts
export const a = 123;

// src/index.ts
import { a } from './a'
import fetch from 'node-fetch'

console.log(a, fetch)

// tsconfig.json
{
 "compilerOptions": {
  "moduleResolution""node",
  "module""commonjs",
  "outDir""dist"
 }
}

// package.json
{
  "name""node-test",
  "version""1.0.0",
  "main""dist/index.js"
}

这是目前 NodeWeb 后端项目的基本配置:

  1. 使用 TS 做类型检查
  2. 使用 TS 作为模块解析工具解析模块,这里一般是 Node,即使用 CommonJS 的模块解析方式
  3. 使用 TS 作为转移工具输出成特定格式的代码,这里一般是 CommonJS 格式


疑惑的源头是 node-fetch



node-fetch@3开始,代码库只提供 ESM 版本,因此如果我们使用最新版,在运行我们的 Node 程序,就会报错:$ tsc && node dist/index.js

/Users/futengda/Desktop/playground/node-test/dist/index.js:4
var node_fetch_1 = require("node-fetch");
                   ^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/futengda/Desktop/playground/node-test/node_modules/.pnpm/[email protected]/node_modules/node-fetch/src/index.js from /Users/futengda/Desktop/playground/node-test/dist/index.js not supported.
Instead change the require of /Users/futengda/Desktop/playground/node-test/node_modules/.pnpm/[email protected]/node_modules/node-fetch/src/index.js in /Users/futengda/Desktop/playground/node-test/dist/index.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/futengda/Desktop/playground/node-test/dist/index.js:4:20) {
  code: 'ERR_REQUIRE_ESM'
}

简化一下是:

require() of ES Module [email protected] from dist/index.js not supported. Instead change the require to a dynamic import().

这里有两个信息,一个是:require 不能引入 ESM,另一个是:如果一定要引入 ESM 请使用 import 函数。这里我们只讨论前者。

参考:https://nodejs.org/api/esm.html#require

这里引出第一个问题:为什么我写的是 ESM,但是却不允许引入 ESM


我们得到的其实不是 ESM



可以看到 tsconfig.json 中,我们默认使用的是 CommonJS 格式,毕竟 Node 一直用的都是 CommonJS。而问题也正是出自这里,因为我们在 CommonJS 的 dist/index.js 中 require 引入了 ESM 的 node-fetch。

但是,很容易想到,把 tsconfig.json 中的 module 改为 ESNext 不就行了吗?不行,又会有新的错误:

$ tsc && node dist/index.js

(node:77294) Warning: To load an ES module, set "type""module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/futengda/Desktop/playground/node-test/dist/index.js:1
import { a } from './a';
^^^^^^
SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

可以看到,提示说无法使用import声明,这里引出第二个问题:为什么即便转译成ESNext格式的ESM,依然不允许使用 import 声明语句


Node 不知道这是 ESM



上方错误栈可以看到,Node 依然使用 node:internal/modules/cjs/loader 来处理我们的 ESM 文件。提示也很清晰,我们需要主动告知 Node 如何处理该文件,因为 Node 自身无法知道它是什么格式的。告知 Node 这是一个 ESM 的方案有两个,要么把它改成 .mjs,要么package.json加一个 type: module,我们选后者。

$ tsc && node dist/index.js


Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/futengda/Desktop/playground/node-test/dist/a' imported from /Users/futengda/Desktop/playground/node-test/dist/index.js
    at new NodeError (node:internal/errors:372:5)
    at finalizeResolution (node:internal/modules/esm/resolve:437:11)
    at moduleResolve (node:internal/modules/esm/resolve:1009:10)
    at defaultResolve (node:internal/modules/esm/resolve:1218:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:580:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:294:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)
    at link (node:internal/modules/esm/module_job:78:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

这里引出第三个问题:为什么即便Node把它当成ESM处理了,依然 Cannot find module dist/a imported from dist/index.js


Node 不认识这种格式的 ESM



”这种格式的 ESM“,这段话让人很费解,难道 ESM 格式还有多种格式?算是吧,虽然ESM标准只有一个,但是ESM的实现各有不同,这里我个人理解成两大类:

  1. ESM 运行时实现
    • Node 的 ESM 运行环境
    • Browser的 ESM 运行环境
  2. ESM 编译时实现
    • Rollup/Webpack/ESBuild 的 ESM 的 打包构建 能力
    • TypeScript/Babel/SWC 的 ESM 的 转译成其他格式 能力
    • Vite 的 ESM 的 bare import转url import 能力

对于 ESM 实现的不同主要体现在如何处理 ESM 格式代码中的模块解析这方面,也就是如何处理 from 后面的 module specifier。

对于运行时实现的模块解析,就是完全遵从 ESM 标准,只不过 Node (现在)相比 Browser 更为强大,除了相对、绝对路径的 module specifier,还可以借助 package.json 的 exports 字段支持 bare specifier。

参考:https://nodejs.org/api/esm.html#import-specifiers 当然浏览器也可能通过 imports-map 来支持 bare specifier,可以期待一下。

而对于编译时实现,虽然我们写的代码是使用 ESM 格式,但是模块解析时却依然走的是 CommonJS 那老一套。因此,当我们在 tsconfig.json 中指定 module 为 esnext 时,其实是想让 TS 生成一个以 CommonJS 方式解析模块的 ESM 格式的代码。

为什么依然走的是老一套?因为历史问题,”自古以来“前端工程化都是基于 Node 的 CommonJS 规范。不过在 Node18 ESM稳定之后,相信历史进程将会推进。

所以,当你告诉 Node,让它使用标准的 ESM 运行时去运行一个“本来打算以 CommonJS 方式解析模块的ESM文件”时,就会出问题,因为这不是Node ESM运行时所支持的 ESM格式。

那么,怎么产出一个 Node ESM运行时支持的 ESM 格式呢?这就回到了最开始的问题,那就是 TS4.7 新推出的 ESM 能力。可以通过在 tsconfig.json 中指定 module 为 nodenext 来实现,现在我们再试一次:

$ tsc && node dist/index.js

error TS2835: Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './a.js'?

1 import { a } from './a'
                    ~~~~~
Found 1 error in src/index.ts:1

又报错了?不过这问题不大,因为现在 TS 可以检测出这段代码不符合 Node ESM 规范,这正是我们想要的。只需要把 ./a 改为 ./a.js 即可,不要觉得在 ts 里写 .js 奇怪,这就是标准写法。


结尾:为什么 ESM 又被发布了一次?



一直有的是:以 CommonJS 作为模块解析方式的 ESM 格式 新发布的是:以 ESM 标准作为模块解析方式的 ESM 格式。

一个很重要的事情是,要明白自己所写的 ESM 到底是运行在什么样的环境里。




关注「Alibaba F2E」微信公众号把握阿里巴巴前端新动向


微信扫码关注该文公众号作者

戳这里提交新闻线索和高质量文章给我们。
相关阅读
博士龙:十二个医学误区Adobe Illustrator 的替代品 Inkscape 发布了 1.2 版本 | Linux 中国2023QS世界大学排名重磅发布!/2022年申请F1学生签证新变化/CollegeBoard提前公布2023年AP考试时间又被最新研究结果吓了一跳:在人入睡的时候,癌细胞会复苏?魁地奇比赛改名“四球”,和JK罗琳划清界限,她又被魔法世界开除一次老罗看上的AR,蔚来要抢先发布了?美国国会开了场关于UFO(UAP)的听证会,现场发布了2段“猛料”19万搞定年轻人的第一台奔驰!全新纯电smart为什么这么火?陀螺研究院:2022年上半年Quest2出货量约590万台,Quest系列累计出货量达1770万台;Meta Q2 财报公布增22844例!即将暴发新一波疫情?病例可能倍增!法国雷暴来袭!芬兰今天宣布了这一次,苹果又被高通拿捏了?退休之地搜寻记 (3)烤包子,烤馄饨,烤坚果 /上海菜肉价完成Xilinx收购后,AMD发布了一款机器人产品使用 OpenSMTPD 将邮件中继到多个 smarthost | Linux 中国硬核观察 #686 一家中国公司发布了首款 RISC-V 笔记本电脑?陆国平教授:2021-2022血脂领域新进展 | OCC 2022广州排名第一的国际部,2022届美国大学录取榜单公布了...我收到了一个电子手环,几小时后它又被拿走了Bridesmaids Go ProfessionalThe Small Group Rescuing Animals During Shanghai Lockdown今年摇号又是一场“血战”?这所协和老牌校,刚发布了这些新变化……硬核观察 #715 Linus 在 Macbook 上发布了 Linux 内核 5.19RSM Global已开放金融类2022 Industrial Placement!刚刚!他和维州州长在Box Hill宣布了一件大事!The Questionable ‘Chinese-ness’ of Chinese Sci-FiA Small Border City Grapples With Post-Lockdown SurvivalHurun China Metaverse Companies with the Greatest Potential 2022精选SDE岗位 | Autodesk、RSM US LLP、Battelle等公司最新职位发布!黄红云又被动失去了一点金科网易在520发布会上,发布了几款「王炸」级的新品说起爱情(三)2022年上半年全球新晋独角兽企业194家,平均估值同比下降15.9%——创业邦发布《2022年上半年全球独角兽企业观察》Chinese Cities Loosen Housing Policies for Three-Child Families疫情3年,地球发生的惊人变化!
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。