ES 模块
本指南帮助解释什么是 ES 模块,以及如何使 Nuxt 应用(或上游库)与 ESM 兼容。
背景
CommonJS 模块
CommonJS(CJS)是 Node.js 引入的一种格式,允许在隔离的 JavaScript 模块之间共享功能(了解更多)。 你可能已经熟悉这种语法:
const a = require('./a')
module.exports.a = a
像 Webpack 和 Rollup 这样的打包工具支持这种语法,并允许你在浏览器中使用 CommonJS 编写的模块。
ESM 语法
大多数情况下,当人们谈论 ESM 与 CJS 时,他们是在讨论用于编写模块的不同语法。
import a from './a'
export { a }
在 ECMAScript 模块(ESM)成为标准之前(这花了十多年时间!),像 Webpack 甚至 TypeScript 这样的工具和语言开始支持所谓的 ESM 语法。 然而,与实际规范有一些关键差异;这里有一个有用的解释。
什么是“原生” ESM?
你可能早已使用 ESM 语法编写应用。毕竟,浏览器原生支持它,在 Nuxt 2 中,我们会将你编写的代码编译为适合的格式(服务器端用 CJS,浏览器端用 ESM)。
在添加模块到你的包时,情况略有不同。一个示例库可能同时暴露 CJS 和 ESM 版本,让我们选择需要的版本:
{
"name": "sample-library",
"main": "dist/sample-library.cjs.js",
"module": "dist/sample-library.esm.js"
}
在 Nuxt 2 中,打包工具(Webpack)会为服务器端构建拉取 CJS 文件('main'),并为客户端构建使用 ESM 文件('module')。
然而,在最近的 Node.js LTS 版本中,现在可以在 Node.js 中使用原生 ESM 模块。这意味着 Node.js 本身可以处理使用 ESM 语法的 JavaScript,尽管它默认不这样做。启用 ESM 语法的两种最常见方式是:
- 在
package.json
中设置"type": "module"
,并继续使用.js
扩展名。 - 使用
.mjs
文件扩展名(推荐)。
这就是我们在 Nuxt Nitro 中所做的;我们输出一个 .output/server/index.mjs
文件。这告诉 Node.js 将该文件视为原生 ES 模块。
在 Node.js 上下文中,什么是有效的导入?
当你使用 import
而不是 require
导入模块时,Node.js 的解析方式不同。例如,当你导入 sample-library
时,Node.js 不会查找 main
,而是查找该库 package.json
中的 exports
或 module
条目。
这也适用于动态导入,例如 const b = await import('sample-library')
。
Node.js 支持以下几种导入类型(参见文档):
- 以
.mjs
结尾的文件 - 这些文件预期使用 ESM 语法。 - 以
.cjs
结尾的文件 - 这些文件预期使用 CJS 语法。 - 以
.js
结尾的文件 - 这些文件预期使用 CJS 语法,除非其package.json
中有"type": "module"
。
可能会出现哪些问题?
长期以来,模块作者一直在生成 ESM 语法的构建版本,并使用类似 .esm.js
或 .es.js
的约定,将其添加到 package.json
的 module
字段中。直到现在这都没有问题,因为它们仅被 Webpack 等打包工具使用,这些工具并不特别关心文件扩展名。
然而,如果你在 Node.js ESM 上下文中尝试导入带有 .esm.js
文件的包,将无法工作,你可能会遇到类似以下错误:
(node:22145) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
/path/to/index.js:1
export default {}
^^^^^^
SyntaxError: Unexpected token 'export'
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
....
at async Object.loadESM (internal/process/esm_loader.js:68:5)
如果你从 Node.js 认为是 CJS 的 ESM 语法构建中进行命名导入,也可能会遇到此错误:
file:///path/to/index.mjs:5
import { named } from 'sample-library'
^^^^^
SyntaxError: Named export 'named' not found. The requested module 'sample-library' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'sample-library';
const { named } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:120:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:165:5)
at async Loader.import (internal/modules/esm/loader.js:177:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
排查 ESM 问题
如果遇到这些错误,问题几乎肯定出在上游库上。他们需要修复他们的库以支持被 Node.js 导入。
转译库
在此期间,你可以告诉 Nuxt 不要尝试导入这些库,方法是将它们添加到 build.transpile
中:
export default defineNuxtConfig({
build: {
transpile: ['sample-library']
}
})
你可能会发现还需要添加这些库导入的其他包。
别名库
在某些情况下,你可能还需要手动将库别名为 CJS 版本,例如:
export default defineNuxtConfig({
alias: {
'sample-library': 'sample-library/dist/sample-library.cjs.js'
}
})
默认导出
采用 CommonJS 格式的依赖项可以使用 module.exports
或 exports
提供默认导出:
module.exports = { test: 123 }
// 或
exports.test = 123
如果我们使用 require
引入此类依赖,通常可以正常工作:
const pkg = require('cjs-pkg')
console.log(pkg) // { test: 123 }
Node.js 在原生 ESM 模式下、启用 esModuleInterop
的 TypeScript 和像 Webpack 这样的打包工具提供了一种兼容机制,使我们可以默认导入此类库。
这种机制通常被称为“互操作默认导入”:
import pkg from 'cjs-pkg'
console.log(pkg) // { test: 123 }
然而,由于语法检测和不同打包格式的复杂性,互操作默认导入可能会失败,导致以下情况:
import pkg from 'cjs-pkg'
console.log(pkg) // { default: { test: 123 } }
在使用动态导入语法(在 CJS 和 ESM 文件中)时,我们总是会遇到这种情况:
import('cjs-pkg').then(console.log) // [Module: null prototype] { default: { test: '123' } }
在这种情况下,我们需要手动互操作默认导出:
// 静态导入
import { default as pkg } from 'cjs-pkg'
// 动态导入
import('cjs-pkg').then(m => m.default || m).then(console.log)
为了处理更复杂的情况并提高安全性,我们推荐并在 Nuxt 内部使用 mlly,它可以保留命名导出。
import { interopDefault } from 'mlly'
// 假设结构为 { default: { foo: 'bar' }, baz: 'qux' }
import myModule from 'my-module'
console.log(interopDefault(myModule)) // { foo: 'bar', baz: 'qux' }
库作者指南
好消息是修复 ESM 兼容性问题相对简单。主要有两种选择:
- 将你的 ESM 文件重命名为以
.mjs
结尾。
这是推荐且最简单的方法。 你可能需要解决库依赖项的问题,以及可能的构建系统问题,但在大多数情况下,这应该能解决问题。还建议将 CJS 文件重命名为以.cjs
结尾,以获得最大的明确性。 - 选择使你的整个库仅使用 ESM。
这意味着在你的package.json
中设置"type": "module"
,并确保构建的库使用 ESM 语法。然而,你可能会遇到依赖项的问题——这种方法意味着你的库只能在 ESM 上下文中使用。
迁移
从 CJS 到 ESM 的初步步骤是将任何使用 require
的地方更新为使用 import
:
module.exports = ...
exports.hello = ...
export default ...
export const hello = ...
const myLib = require('my-lib')
import myLib from 'my-lib'
// 或
const myLib = await import('my-lib').then(lib => lib.default || lib)
在 ESM 模块中,与 CJS 不同,require
、require.resolve
、__filename
和 __dirname
全局变量不可用,应替换为 import()
和 import.meta.filename
。
import { join } from 'path'
const newDir = join(__dirname, 'new-dir')
import { fileURLToPath } from 'node:url'
const newDir = fileURLToPath(new URL('./new-dir', import.meta.url))
const someFile = require.resolve('./lib/foo.js')
import { resolvePath } from 'mlly'
const someFile = await resolvePath('my-lib', { url: import.meta.url })
最佳实践
- 优先使用命名导出而非默认导出。这有助于减少 CJS 冲突。(参见默认导出部分)
- 尽量避免依赖 Node.js 内置模块和仅限 CommonJS 或 Node.js 的依赖项,以使你的库可在浏览器和边缘工作者中使用,而无需 Nitro 填充。
- 使用新的
exports
字段并带条件导出。(了解更多)。
{
"exports": {
".": {
"import": "./dist/mymodule.mjs"
}
}
}