ES 模块
本指南将解释什么是 ES 模块,以及如何使 Nuxt 应用程序(或上游库)与 ESM 兼容。
背景
CommonJS 模块
CommonJS (CJS) 是 Node.js 引入的一种格式,允许在独立的 JavaScript 模块之间共享功能(阅读更多)。你可能已经熟悉这种语法。
const a = require('./a')
module.exports.a = a
像 webpack 和 Rollup 这样的打包工具支持这种语法,并允许你在浏览器中使用用 CommonJS 编写的模块。
ESM 语法
大多数情况下,当人们谈论 ESM 与 CJS 时,他们指的是编写代码的不同语法。modules.
import a from './a'
export { a }
在 ECMAScript 模块 (ESM) 成为标准之前(这花费了 10 多年!),像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 会在该库的 package.json
中查找 exports
条目,如果 exports
未定义,则回退到 main
条目。
动态导入也是如此,例如 const b = await import('sample-library')
。
Node 支持以下类型的导入(参见文档):
- 以
.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 导入。
转译库
在此期间,你可以通过将这些库添加到 build.transpile
来告诉 Nuxt 不要尝试导入它们。
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 }
// or
exports.test = 123
如果我们 require
这样的依赖项,这通常运行良好。
const pkg = require('cjs-pkg')
console.log(pkg) // { test: 123 }
Node.js 在原生 ESM 模式下, 启用 esModuleInterop
的 TypeScript以及像 webpack 这样的打包工具提供了一种兼容机制,使我们能够默认导入此类库。这种机制通常被称为“interop require default”。
import pkg from 'cjs-pkg'
console.log(pkg) // { test: 123 }
然而,由于语法检测和不同打包格式的复杂性,总是存在 interop default 失败的可能性,最终导致类似以下情况:
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' } }
在这种情况下,我们需要手动进行默认导出的互操作。
// Static import
import { default as pkg } from 'cjs-pkg'
// Dynamic import
import('cjs-pkg').then(m => m.default || m).then(console.log)
为了处理更复杂的情况和更高的安全性,我们推荐并在 Nuxt 内部使用mlly,它可以保留具名导出。
import { interopDefault } from 'mlly'
// Assuming the shape is { 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 = function () { /* ... */ }
exports.hello = 'world'
export default function () { /* ... */ }
export const hello = 'world'
const myLib = require('my-lib')
import myLib from 'my-lib'
// or
const dynamicMyLib = await import('my-lib').then(lib => lib.default || lib)
在 ESM 模块中,与 CJS 不同,require
、require.resolve
、__filename
和 __dirname
全局变量不可用,应替换为 import()
和 import.meta.filename
。
const { join } = require('node: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 的依赖项,以使你的库在浏览器和 Edge Workers 中无需 Nitro polyfills 即可使用。
- 使用带有条件导出的新
exports
字段。(阅读更多).
{
"exports": {
".": {
"import": "./dist/mymodule.mjs"
}
}
}