Node.js v18.18.0 文档


模块:ECMAScript 模块#

稳定性: 2 - 稳定

介绍#

ECMAScript 模块是 官方标准格式,用于打包 JavaScript 代码以供重用。 模块使用各种 importexport 语句定义。

ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements.

以下是 ES 模块导出函数的示例:

The following example of an ES module exports a function:

// addTwo.mjs
function addTwo(num) {
  return num + 2;
}

export { addTwo }; 

以下是 ES 模块从 addTwo.mjs 导入函数的示例:

The following example of an ES module imports the function from addTwo.mjs:

// app.mjs
import { addTwo } from './addTwo.mjs';

// Prints: 6
console.log(addTwo(4)); 

Node.js 完全支持当前指定的 ECMAScript 模块,并提供它们与其原始模块格式 CommonJS 之间的互操作性。

Node.js fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS.

启用#

Node.js 有两个模块系统: CommonJS 模块和 ECMAScript 模块。

Node.js has two module systems: CommonJS modules and ECMAScript modules.

作者可以通过 .mjs 文件扩展名、package.json "type" 字段、或 --input-type 标志告诉 Node.js 使用 ECMAScript 模块加载器。 在这些情况之外,Node.js 将使用 CommonJS 模块加载器。 有关详细信息,请参阅 确定模块系统

Authors can tell Node.js to use the ECMAScript modules loader via the .mjs file extension, the package.json "type" field, or the --input-type flag. Outside of those cases, Node.js will use the CommonJS module loader. See Determining module system for more details.

#

此部分已移至 模块:包

This section was moved to Modules: Packages.

import 说明符#

术语#

import 语句的说明符是 from 关键字之后的字符串,例如 import { sep } from 'node:path' 中的 'node:path'。 说明符也用于 export from 语句,并作为 import() 表达式的参数。

The specifier of an import statement is the string after the from keyword, e.g. 'node:path' in import { sep } from 'node:path'. Specifiers are also used in export from statements, and as the argument to an import() expression.

有三种类型的说明符:

There are three types of specifiers:

  • 相对说明符,如 './startup.js''../config.mjs'。 它们指的是相对于导入文件位置的路径。 这些文件扩展名始终是必需的。

  • 纯说明符,如 'some-package''some-package/shuffle'。 它们可以通过包名称来引用包的主要入口点,或者根据示例分别以包名称为前缀的包中的特定功能模块。 只有没有 "exports" 字段的包才需要包含文件扩展名。

  • 绝对说明符,如 'file:///opt/nodejs/config.js'。 它们直接且明确地引用完整的路径。

裸说明符解析由 Node.js 模块解析和加载算法 处理。 所有其他说明符解析始终仅使用标准的相对 URL 解析语义进行解析。

Bare specifier resolutions are handled by the Node.js module resolution and loading algorithm. All other specifier resolutions are always only resolved with the standard relative URL resolution semantics.

就像在 CommonJS 中一样,包中的模块文件可以通过在包名称后附加路径来访问,除非包的 package.json 包含 "exports" 字段,在这种情况下,包中的文件只能通过 "exports" 中定义的路径访问。

Like in CommonJS, module files within packages can be accessed by appending a path to the package name unless the package's package.json contains an "exports" field, in which case files within packages can only be accessed via the paths defined in "exports".

有关适用于 Node.js 模块解析中的裸说明符的这些包解析规则的详细信息,请参阅 包文档

For details on these package resolution rules that apply to bare specifiers in the Node.js module resolution, see the packages documentation.

强制文件扩展名#

当使用 import 关键字解析相对或绝对的说明符时,必须提供文件扩展名。 还必须完全指定目录索引(例如 './startup/index.js')。

A file extension must be provided when using the import keyword to resolve relative or absolute specifiers. Directory indexes (e.g. './startup/index.js') must also be fully specified.

此行为与 import 在浏览器环境中的行为方式相匹配,假设服务器是典型配置的。

This behavior matches how import behaves in browser environments, assuming a typically configured server.

URL#

ES 模块被解析并缓存为 URL。 这意味着特殊字符必须是 percent-encoded,例如 # 必须是 %23? 必须是 %3F

ES modules are resolved and cached as URLs. This means that special characters must be percent-encoded, such as # with %23 and ? with %3F.

支持 file:node:data: URL 协议。 除非使用 自定义 HTTPS 加载器,否则 Node.js 本身不支持像 'https://example.com/app.js' 这样的说明符。

file:, node:, and data: URL schemes are supported. A specifier like 'https://example.com/app.js' is not supported natively in Node.js unless using a custom HTTPS loader.

file: 个网址#

如果用于解析模块的 import 说明符具有不同的查询或片段,则会多次加载模块。

Modules are loaded multiple times if the import specifier used to resolve them has a different query or fragment.

import './foo.mjs?query=1'; // loads ./foo.mjs with query of "?query=1"
import './foo.mjs?query=2'; // loads ./foo.mjs with query of "?query=2" 

可以通过 ///、或 file:/// 引用卷根。 考虑到 URL 和路径解析的差异(比如百分比编码细节),建议导入路径时使用 url.pathToFileURL

The volume root may be referenced via /, //, or file:///. Given the differences between URL and path resolution (such as percent encoding details), it is recommended to use url.pathToFileURL when importing a path.

data: 导入#

data: 个网址 支持使用以下 MIME 类型导入:

data: URLs are supported for importing with the following MIME types:

  • text/javascript 用于 ES 模块
  • application/json 用于 JSON
  • application/wasm 用于 Wasm
import 'data:text/javascript,console.log("hello!");';
import _ from 'data:application/json,"world!"' assert { type: 'json' }; 

data: URL 仅解析内置模块的 裸说明符绝对说明符。 解析 相对说明符 不起作用,因为 data: 不是 特别计划。 例如,尝试从 data:text/javascript,import "./foo"; 加载 ./foo 无法解析,因为 data: URL 没有相对解析的概念。

data: URLs only resolve bare specifiers for builtin modules and absolute specifiers. Resolving relative specifiers does not work because data: is not a special scheme. For example, attempting to load ./foo from data:text/javascript,import "./foo"; fails to resolve because there is no concept of relative resolution for data: URLs.

node: 导入#

node: 支持 URL 作为加载 Node.js 内置模块的替代方法。 此 URL 协议允许有效的绝对的 URL 字符串引用内置模块。

node: URLs are supported as an alternative means to load Node.js builtin modules. This URL scheme allows for builtin modules to be referenced by valid absolute URL strings.

import fs from 'node:fs/promises'; 

导入断言#

稳定性: 1 - 实验

导入断言提案 为模块导入语句添加了内联语法,以便在模块说明符旁边传递更多信息。

The Import Assertions proposal adds an inline syntax for module import statements to pass on more information alongside the module specifier.

import fooData from './foo.json' assert { type: 'json' };

const { default: barData } =
  await import('./bar.json', { assert: { type: 'json' } }); 

Node.js 支持以下 type 值,其断言是强制性的:

Node.js supports the following type values, for which the assertion is mandatory:

断言 type需要的
'json'JSON 模块

内置模块#

核心模块 提供其公共 API 的命名导出。 还提供了默认导出,其是 CommonJS 导出的值。 默认导出可用于修改命名导出等。 内置模块的命名导出仅通过调用 module.syncBuiltinESMExports() 进行更新。

Core modules provide named exports of their public API. A default export is also provided which is the value of the CommonJS exports. The default export can be used for, among other things, modifying the named exports. Named exports of builtin modules are updated only by calling module.syncBuiltinESMExports().

import EventEmitter from 'node:events';
const e = new EventEmitter(); 
import { readFile } from 'node:fs';
readFile('./foo.txt', (err, source) => {
  if (err) {
    console.error(err);
  } else {
    console.log(source);
  }
}); 
import fs, { readFileSync } from 'node:fs';
import { syncBuiltinESMExports } from 'node:module';
import { Buffer } from 'node:buffer';

fs.readFileSync = () => Buffer.from('Hello, ESM');
syncBuiltinESMExports();

fs.readFileSync === readFileSync; 

import() 表达式#

CommonJS 和 ES 模块都支持 动态 import()。 在 CommonJS 模块中它可以用来加载 ES 模块。

Dynamic import() is supported in both CommonJS and ES modules. In CommonJS modules it can be used to load ES modules.

import.meta#

import.meta 元属性是包含以下属性的 Object

The import.meta meta property is an Object that contains the following properties.

import.meta.url#

  • <string> 模块的绝对的 file: URL。

这与提供当前模块文件 URL 的浏览器中的定义完全相同。

This is defined exactly the same as it is in browsers providing the URL of the current module file.

这可以启用有用的模式,例如相对文件加载

This enables useful patterns such as relative file loading:

import { readFileSync } from 'node:fs';
const buffer = readFileSync(new URL('./data.proto', import.meta.url)); 

import.meta.resolve(specifier[, parent])#

稳定性: 1 - 实验

此特性仅在启用 --experimental-import-meta-resolve 命令标志时可用。

This feature is only available with the --experimental-import-meta-resolve command flag enabled.

  • specifier <string> 相对于 parent 解析的模块说明符。
  • parent <string> | <URL> 要解析的绝对的父模块 URL。 如果未指定,则使用 import.meta.url 的值作为默认值。
  • 返回: <Promise>

提供作用域为每个模块的模块相关解析函数,返回 URL 字符串。

Provides a module-relative resolution function scoped to each module, returning the URL string.

const dependencyAsset = await import.meta.resolve('component-lib/asset.css'); 

import.meta.resolve 还接受第二个参数,它是从中解析的父模块:

import.meta.resolve also accepts a second argument which is the parent module from which to resolve from:

await import.meta.resolve('./dep', import.meta.url); 

这个函数是异步的,因为 Node.js 中的 ES 模块解析器是允许异步的。

This function is asynchronous because the ES module resolver in Node.js is allowed to be asynchronous.

与 CommonJS 的互操作性#

import 语句#

import 语句可以引用 ES 模块或 CommonJS 模块。 import 语句只允许在 ES 模块中使用,但 CommonJS 支持动态 import() 表达式来加载 ES 模块。

An import statement can reference an ES module or a CommonJS module. import statements are permitted only in ES modules, but dynamic import() expressions are supported in CommonJS for loading ES modules.

导入 CommonJS 模块 时,module.exports 对象作为默认导出提供。 命名导出可能可用,由静态分析提供,以方便更好的生态系统兼容性。

When importing CommonJS modules, the module.exports object is provided as the default export. Named exports may be available, provided by static analysis as a convenience for better ecosystem compatibility.

require#

CommonJS 模块 require 总是将它引用的文件视为 CommonJS。

The CommonJS module require always treats the files it references as CommonJS.

不支持使用 require 加载 ES 模块,因为 ES 模块具有异步执行。 而是,使用 import() 从 CommonJS 模块加载 ES 模块。

Using require to load an ES module is not supported because ES modules have asynchronous execution. Instead, use import() to load an ES module from a CommonJS module.

CommonJS 命名空间#

CommonJS 模块由可以是任何类型的 module.exports 对象组成。

CommonJS modules consist of a module.exports object which can be of any type.

当导入 CommonJS 模块时,可以使用 ES 模块默认导入或其对应的语法糖可靠地导入:

When importing a CommonJS module, it can be reliably imported using the ES module default import or its corresponding sugar syntax:

import { default as cjs } from 'cjs';

// The following import statement is "syntax sugar" (equivalent but sweeter)
// for `{ default as cjsSugar }` in the above import statement:
import cjsSugar from 'cjs';

console.log(cjs);
console.log(cjs === cjsSugar);
// Prints:
//   <module.exports>
//   true 

CommonJS 模块的 ECMAScript 模块命名空间表示始终是使用 default 导出键指向 CommonJS module.exports 值的命名空间。

The ECMAScript Module Namespace representation of a CommonJS module is always a namespace with a default export key pointing to the CommonJS module.exports value.

当使用 import * as m from 'cjs' 或动态导入时,可以直接观察到此模块命名空间外来对象:

This Module Namespace Exotic Object can be directly observed either when using import * as m from 'cjs' or a dynamic import:

import * as m from 'cjs';
console.log(m);
console.log(m === await import('cjs'));
// Prints:
//   [Module] { default: <module.exports> }
//   true 

为了更好地兼容 JS 生态系统中的现有用法,Node.js 还尝试确定每个导入的 CommonJS 模块的 CommonJS 命名导出,以使用静态分析过程将它们作为单独的 ES 模块导出提供。

For better compatibility with existing usage in the JS ecosystem, Node.js in addition attempts to determine the CommonJS named exports of every imported CommonJS module to provide them as separate ES module exports using a static analysis process.

例如,考虑编写的 CommonJS 模块:

For example, consider a CommonJS module written:

// cjs.cjs
exports.name = 'exported'; 

前面的模块支持 ES 模块中的命名导入:

The preceding module supports named imports in ES modules:

import { name } from './cjs.cjs';
console.log(name);
// Prints: 'exported'

import cjs from './cjs.cjs';
console.log(cjs);
// Prints: { name: 'exported' }

import * as m from './cjs.cjs';
console.log(m);
// Prints: [Module] { default: { name: 'exported' }, name: 'exported' } 

从上一个记录模块命名空间外来对象的示例中可以看出,name 导出是从 module.exports 对象复制出来的,并在导入模块时直接设置在 ES 模块命名空间上。

As can be seen from the last example of the Module Namespace Exotic Object being logged, the name export is copied off of the module.exports object and set directly on the ES module namespace when the module is imported.

未检测到这些命名导出的实时绑定更新或添加到 module.exports 的新导出。

Live binding updates or new exports added to module.exports are not detected for these named exports.

命名导出的检测基于通用语法模式,但并不总是正确地检测命名导出。 在这些情况下,使用上述默认导入形式可能是更好的选择。

The detection of named exports is based on common syntax patterns but does not always correctly detect named exports. In these cases, using the default import form described above can be a better option.

命名导出检测涵盖了许多常见的导出模式、再导出模式、以及构建工具和转译器输出。 有关实现的确切语义,请参阅 cjs-module-lexer

Named exports detection covers many common export patterns, reexport patterns and build tool and transpiler outputs. See cjs-module-lexer for the exact semantics implemented.

ES 模块和 CommonJS 的区别#

requireexportsmodule.exports#

在大多数情况下,可以使用 ES 模块 import 加载 CommonJS 模块。

In most cases, the ES module import can be used to load CommonJS modules.

如果需要,可以使用 module.createRequire() 在 ES 模块中构造 require 函数。

If needed, a require function can be constructed within an ES module using module.createRequire().

__filename__dirname#

这些 CommonJS 变量在 ES 模块中不可用。

These CommonJS variables are not available in ES modules.

__filename__dirname 用例可以通过 import.meta.url 复制。

__filename and __dirname use cases can be replicated via import.meta.url.

没有插件加载#

插件 当前不支持 ES 模块导入。

Addons are not currently supported with ES module imports.

它们可以改为加载 module.createRequire()process.dlopen

They can instead be loaded with module.createRequire() or process.dlopen.

没有 require.resolve#

相对解析可以通过 new URL('./local', import.meta.url) 处理。

Relative resolution can be handled via new URL('./local', import.meta.url).

对于完整的 require.resolve 替换,有标记的实验性 import.meta.resolve API。

For a complete require.resolve replacement, there is a flagged experimental import.meta.resolve API.

也可以使用 module.createRequire()

Alternatively module.createRequire() can be used.

没有 NODE_PATH#

NODE_PATH 不是解析 import 说明符的一部分。 如果需要这种行为,则使用符号链接。

NODE_PATH is not part of resolving import specifiers. Please use symlinks if this behavior is desired.

没有 require.extensions#

require.extensions 没有被 import 使用。 期望加载器钩子在未来可以提供这个工作流。

require.extensions is not used by import. The expectation is that loader hooks can provide this workflow in the future.

没有 require.cache#

require.cache 没有被 import 使用,因为 ES 模块加载器有自己独立的缓存。

require.cache is not used by import as the ES module loader has its own separate cache.

JSON 模块#

稳定性: 1 - 实验

import 可以引用 JSON 文件:

JSON files can be referenced by import:

import packageConfig from './package.json' assert { type: 'json' }; 

assert { type: 'json' } 语法是强制性的; 见 导入断言

The assert { type: 'json' } syntax is mandatory; see Import Assertions.

导入的 JSON 只暴露一个 default 导出。 不支持命名导出。 在 CommonJS 缓存中创建缓存条目,以避免重复。 如果 JSON 模块已经从同一路径导入,则在 CommonJS 中返回相同的对象。

The imported JSON only exposes a default export. There is no support for named exports. A cache entry is created in the CommonJS cache to avoid duplication. The same object is returned in CommonJS if the JSON module has already been imported from the same path.

Wasm 模块#

稳定性: 1 - 实验

--experimental-wasm-modules 标志下支持导入 WebAssembly 模块,允许将任何 .wasm 文件作为普通模块导入,同时也支持它们的模块导入。

Importing WebAssembly modules is supported under the --experimental-wasm-modules flag, allowing any .wasm files to be imported as normal modules while also supporting their module imports.

这种整合是符合 WebAssembly 的 ES 模块集成提案 的。

This integration is in line with the ES Module Integration Proposal for WebAssembly.

例如,index.mjs 包含:

For example, an index.mjs containing:

import * as M from './module.wasm';
console.log(M); 

在以下条件下执行:

executed under:

node --experimental-wasm-modules index.mjs 

将为 module.wasm 的实例化提供导出接口。

would provide the exports interface for the instantiation of module.wasm.

顶层 await#

await 关键字可以用在 ECMAScript 模块的顶层主体中。

The await keyword may be used in the top level body of an ECMAScript module.

假设 a.mjs 具有

Assuming an a.mjs with

export const five = await Promise.resolve(5); 

并且 b.mjs 具有

And a b.mjs with

import { five } from './a.mjs';

console.log(five); // Logs `5` 
node b.mjs # works 

如果顶层 await 表达式永远无法解析,则 node 进程将退出并返回 13 状态码

If a top level await expression never resolves, the node process will exit with a 13 status code.

import { spawn } from 'node:child_process';
import { execPath } from 'node:process';

spawn(execPath, [
  '--input-type=module',
  '--eval',
  // Never-resolving Promise:
  'await new Promise(() => {})',
]).once('exit', (code) => {
  console.log(code); // Logs `13`
}); 

HTTPS 和 HTTP 导入#

稳定性: 1 - 实验

--experimental-network-imports 标志下支持使用 https:http: 导入基于网络的模块。 这允许类似网络浏览器的导入在 Node.js 中工作,但由于应用稳定性和安全问题在特权环境而不是浏览器沙箱中运行时会有所不同,因此存在一些差异。

Importing network based modules using https: and http: is supported under the --experimental-network-imports flag. This allows web browser-like imports to work in Node.js with a few differences due to application stability and security concerns that are different when running in a privileged environment instead of a browser sandbox.

导入仅限于 HTTP/1#

尚不支持 HTTP/2 和 HTTP/3 的自动协议协商。

Automatic protocol negotiation for HTTP/2 and HTTP/3 is not yet supported.

HTTP 仅限于环回地址#

http: 易受中间人攻击,不允许用于 IPv4 地址 127.0.0.0/8127.0.0.1127.255.255.255)和 IPv6 地址 ::1 之外的地址。 对 http: 的支持旨在用于本地开发。

http: is vulnerable to man-in-the-middle attacks and is not allowed to be used for addresses outside of the IPv4 address 127.0.0.0/8 (127.0.0.1 to 127.255.255.255) and the IPv6 address ::1. Support for http: is intended to be used for local development.

身份验证永远不会发送到目标服务器。#

AuthorizationCookieProxy-Authorization 标头未发送到服务器。 避免在部分导入的 URL 中包含用户信息。 正在研究在服务器上安全使用这些的安全模型。

Authorization, Cookie, and Proxy-Authorization headers are not sent to the server. Avoid including user info in parts of imported URLs. A security model for safely using these on the server is being worked on.

永远不会在目标服务器上检查 CORS#

CORS 旨在允许服务器将 API 的使用者限制为一组特定的主机。 这不受支持,因为它对于基于服务器的实现没有意义。

CORS is designed to allow a server to limit the consumers of an API to a specific set of hosts. This is not supported as it does not make sense for a server-based implementation.

无法加载非网络依赖#

这些模块不能访问不超过 http:https: 的其他模块。 要在避免安全问题的同时仍然访问本地模块,则传入对本地依赖的引用:

These modules cannot access other modules that are not over http: or https:. To still access local modules while avoiding the security concern, pass in references to the local dependencies:

// file.mjs
import worker_threads from 'node:worker_threads';
import { configure, resize } from 'https://example.com/imagelib.mjs';
configure({ worker_threads }); 
// https://example.com/imagelib.mjs
let worker_threads;
export function configure(opts) {
  worker_threads = opts.worker_threads;
}
export function resize(img, size) {
  // Perform resizing in worker_thread to avoid main thread blocking
} 

默认情况下不启用基于网络的加载#

目前,需要 --experimental-network-imports 标志来启用通过 http:https: 加载资源。 将来,将使用不同的机制来执行此操作。 需要选择加入以防止不经意间使用可能影响 Node.js 应用可靠性的潜在可变状态的传递依赖。

For now, the --experimental-network-imports flag is required to enable loading resources over http: or https:. In the future, a different mechanism will be used to enforce this. Opt-in is required to prevent transitive dependencies inadvertently using potentially mutable state that could affect reliability of Node.js applications.

加载器#

稳定性: 1 - 实验

此 API 目前正在重新设计,并且仍会发生变化。

要自定义默认的模块解析,则可以选择通过 Node.js 的 --experimental-loader ./loader-name.mjs 参数提供加载器钩子。

To customize the default module resolution, loader hooks can optionally be provided via a --experimental-loader ./loader-name.mjs argument to Node.js.

使用钩子时,它们适用于入口点和所有 import 调用。 它们不适用于 require 调用; 那些仍然遵循 CommonJS 规则。

When hooks are used they apply to the entry point and all import calls. They won't apply to require calls; those still follow CommonJS rules.

加载器遵循 --require 的模式:

Loaders follow the pattern of --require:

node \
  --experimental-loader unpkg \
  --experimental-loader http-to-https \
  --experimental-loader cache-buster 

它们按以下顺序调用: cache-buster 调用 http-to-httpshttp-to-https 调用 unpkg

These are called in the following sequence: cache-buster calls http-to-https which calls unpkg.

钩子#

钩子是链的一部分,即使该链仅由一个自定义(用户提供的)钩子和始终存在的默认钩子组成。 钩子函数嵌套: 每个都必须始终返回一个普通对象,并且链接是由于每个函数调用 next<hookName>() 而发生的,next<hookName>() 是对后续加载程序钩子的引用。

Hooks are part of a chain, even if that chain consists of only one custom (user-provided) hook and the default hook, which is always present. Hook functions nest: each one must always return a plain object, and chaining happens as a result of each function calling next<hookName>(), which is a reference to the subsequent loader’s hook.

返回缺少必需属性的值的钩子会触发异常。 没有调用 next<hookName>() 和没有返回 shortCircuit: true 就返回的钩子也会触发异常。 这些错误有助于防止链中的意外中断。

A hook that returns a value lacking a required property triggers an exception. A hook that returns without calling next<hookName>() and without returning shortCircuit: true also triggers an exception. These errors are to help prevent unintentional breaks in the chain.

resolve(specifier, context, nextResolve)#

加载程序 API 正在重新设计。 这个钩子可能会消失或者它的签名可能会改变。 不要依赖下面描述的 API。

  • specifier <string>
  • context <Object>
    • conditions <string[]> 相关 package.json 的导出条件
    • importAssertions <Object>
    • parentURL <string> | <undefined> 导入此模块的模块,如果这是 Node.js 入口点,则为未定义
  • nextResolve <Function> 链中后续的 resolve 钩子,或者用户提供的最后一个 resolve 钩子之后的 Node.js 默认 resolve 钩子
  • 返回: <Object>
    • format <string> | <null> | <undefined> 加载钩子的提示(可能会被忽略)'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'
    • shortCircuit <undefined> | <boolean> 此钩子打算终止 resolve 钩子链的信号。 默认值: false
    • url <string> 此输入解析到的绝对 URL

resolve 钩子链负责解析给定模块说明符和父 URL 的文件 URL,以及可选的格式(例如 'module')作为 load 钩子的提示。 如果指定了格式,load 钩子最终负责提供最终的 format 值(并且可以随意忽略 resolve 提供的提示); 如果 resolve 提供 format,则需要自定义 load 钩子,即使只是将值传递给 Node.js 默认的 load 钩子。

The resolve hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as 'module') as a hint to the load hook. If a format is specified, the load hook is ultimately responsible for providing the final format value (and it is free to ignore the hint provided by resolve); if resolve provides a format, a custom load hook is required even if only to pass the value to the Node.js default load hook.

模块说明符是 import 语句或 import() 表达式中的字符串。

The module specifier is the string in an import statement or import() expression.

父 URL 是导入此模块的 URL,如果这是应用的主要入口点,则为 undefined

The parent URL is the URL of the module that imported this one, or undefined if this is the main entry point for the application.

context 中的 conditions 属性是适用于此解析请求的 包导出条件 的条件数组。 它们可用于在别处查找条件映射或在调用默认解析逻辑时修改列表。

The conditions property in context is an array of conditions for package exports conditions that apply to this resolution request. They can be used for looking up conditional mappings elsewhere or to modify the list when calling the default resolution logic.

当前的 包导出条件 总是在传入钩子的 context.conditions 数组中。 为了保证在调用 defaultResolve 时默认的 Node.js 模块说明符解析行为,传递给它的 context.conditions 数组必须包括最初传递到 resolve 钩子的 context.conditions 数组的所有元素。

The current package exports conditions are always in the context.conditions array passed into the hook. To guarantee default Node.js module specifier resolution behavior when calling defaultResolve, the context.conditions array passed to it must include all elements of the context.conditions array originally passed into the resolve hook.

export async function resolve(specifier, context, nextResolve) {
  const { parentURL = null } = context;

  if (Math.random() > 0.5) { // Some condition.
    // For some or all specifiers, do some custom logic for resolving.
    // Always return an object of the form {url: <string>}.
    return {
      shortCircuit: true,
      url: parentURL ?
        new URL(specifier, parentURL).href :
        new URL(specifier).href,
    };
  }

  if (Math.random() < 0.5) { // Another condition.
    // When calling `defaultResolve`, the arguments can be modified. In this
    // case it's adding another value for matching conditional exports.
    return nextResolve(specifier, {
      ...context,
      conditions: [...context.conditions, 'another-condition'],
    });
  }

  // Defer to the next hook in the chain, which would be the
  // Node.js default resolve if this is the last user-specified loader.
  return nextResolve(specifier);
} 

load(url, context, nextLoad)#

加载程序 API 正在重新设计。 这个钩子可能会消失或者它的签名可能会改变。 不要依赖下面描述的 API。

在此 API 的先前版本中,它分为 3 个独立的、现已弃用的钩子(getFormatgetSourcetransformSource)。

load 钩子提供了一种方式来定义确定网址应如何解释、检索、以及解析的自定义方法。 它还负责验证导入断言。

The load hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. It is also in charge of validating the import assertion.

format 的最终值必须是以下之一:

The final value of format must be one of the following:

format描述load 返回的 source 的可接受类型
'builtin'加载 Node.js 内置模块不适用
'commonjs'加载 Node.js CommonJS 模块不适用
'json'加载一个 JSON 文件{ string, ArrayBuffer, TypedArray }
'module'加载一个 ES 模块{ string, ArrayBuffer, TypedArray }
'wasm'加载 WebAssembly 模块{ ArrayBuffer, TypedArray }

source 的值对于类型 'builtin' 被忽略,因为目前无法替换 Node.js 内置(核心)模块的值。 对于类型 'commonjs'source 的值被忽略,因为 CommonJS 模块加载器没有为 ES 模块加载器提供覆盖 CommonJS 模块返回值 的机制。 这个限制将来可能会被克服。

The value of source is ignored for type 'builtin' because currently it is not possible to replace the value of a Node.js builtin (core) module. The value of source is ignored for type 'commonjs' because the CommonJS module loader does not provide a mechanism for the ES module loader to override the CommonJS module return value. This limitation might be overcome in the future.

警告: ESM load 钩子和来自 CommonJS 模块的命名空间导出不兼容。 尝试将它们一起使用将导致导入的对象为空。 这可能会在未来得到解决。

这些类型都对应于 ECMAScript 中定义的类。

如果基于文本的格式(即 'json''module')的源值不是字符串,则使用 util.TextDecoder 将其转换为字符串。

If the source value of a text-based format (i.e., 'json', 'module') is not a string, it is converted to a string using util.TextDecoder.

load 钩子提供了一种方法来定义用于检索 ES 模块说明符的源代码的自定义方法。 这将允许加载器潜在地避免从磁盘读取文件。 它还可以用于将无法识别的格式映射到支持的格式,例如 yamlmodule

The load hook provides a way to define a custom method for retrieving the source code of an ES module specifier. This would allow a loader to potentially avoid reading files from disk. It could also be used to map an unrecognized format to a supported one, for example yaml to module.

export async function load(url, context, nextLoad) {
  const { format } = context;

  if (Math.random() > 0.5) { // Some condition
    /*
      For some or all URLs, do some custom logic for retrieving the source.
      Always return an object of the form {
        format: <string>,
        source: <string|buffer>,
      }.
    */
    return {
      format,
      shortCircuit: true,
      source: '...',
    };
  }

  // Defer to the next hook in the chain.
  return nextLoad(url);
} 

在更高级的场景中,这也可用于将不受支持的来源转换为受支持的来源(请参阅下面的 示例)。

In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see Examples below).

globalPreload()#

加载程序 API 正在重新设计。 这个钩子可能会消失或者它的签名可能会改变。 不要依赖下面描述的 API。

在此 API 的先前版本中,此钩子名为 getGlobalPreloadCode

有时可能需要在应用运行所在的同一全局作用域内运行一些代码。 此钩子允许返回在启动时作为宽松模式脚本运行的字符串。

Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. This hook allows the return of a string that is run as a sloppy-mode script on startup.

类似于 CommonJS 封装器的工作方式,代码在隐式函数范围内运行。 唯一的参数是一个类似 require 的函数,可用于加载像 "fs" 这样的内置函数: getBuiltin(request: string)

Similar to how CommonJS wrappers work, the code runs in an implicit function scope. The only argument is a require-like function that can be used to load builtins like "fs": getBuiltin(request: string).

如果代码需要更高级的 require 特性,则必须使用 module.createRequire() 构建自己的 require

If the code needs more advanced require features, it has to construct its own require using module.createRequire().

export function globalPreload(context) {
  return `\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');

const { createRequire } = getBuiltin('module');
const { cwd } = getBuiltin('process');

const require = createRequire(cwd() + '/<preload>');
// [...]
`;
} 

为了允许应用和加载器之间的通信,向预加载代码提供了另一个参数: port。 这可以作为加载器钩子的参数和钩子返回的源文本内部。 必须注意正确调用 port.ref()port.unref() 以防止进程处于无法正常关闭的状态。

In order to allow communication between the application and the loader, another argument is provided to the preload code: port. This is available as a parameter to the loader hook and inside of the source text returned by the hook. Some care must be taken in order to properly call port.ref() and port.unref() to prevent a process from being in a state where it won't close normally.

/**
 * This example has the application context send a message to the loader
 * and sends the message back to the application context
 */
export function globalPreload({ port }) {
  port.onmessage = (evt) => {
    port.postMessage(evt.data);
  };
  return `\
    port.postMessage('console.log("I went to the Loader and back");');
    port.onmessage = (evt) => {
      eval(evt.data);
    };
  `;
} 

示例#

各种加载器钩子可以一起使用来完成对 Node.js 代码加载和评估行为的广泛定制。

The various loader hooks can be used together to accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors.

HTTPS 加载器#

在当前的 Node.js 中,以 https:// 开头的说明符是实验性的(请参阅 HTTPS 和 HTTP 导入)。

In current Node.js, specifiers starting with https:// are experimental (see HTTPS and HTTP imports).

下面的加载器注册钩子以启用对此类说明符的基本支持。 虽然这看起来像是对 Node.js 核心功能的重大改进,但实际使用此加载器有很大的缺点: 性能比从磁盘加载文件慢得多,没有缓存,也没有安全性。

The loader below registers hooks to enable rudimentary support for such specifiers. While this may seem like a significant improvement to Node.js core functionality, there are substantial downsides to actually using this loader: performance is much slower than loading files from disk, there is no caching, and there is no security.

// https-loader.mjs
import { get } from 'node:https';

export function load(url, context, nextLoad) {
  // For JavaScript to be loaded over the network, we need to fetch and
  // return it.
  if (url.startsWith('https://')) {
    return new Promise((resolve, reject) => {
      get(url, (res) => {
        let data = '';
        res.setEncoding('utf8');
        res.on('data', (chunk) => data += chunk);
        res.on('end', () => resolve({
          // This example assumes all network-provided JavaScript is ES module
          // code.
          format: 'module',
          shortCircuit: true,
          source: data,
        }));
      }).on('error', (err) => reject(err));
    });
  }

  // Let Node.js handle all other URLs.
  return nextLoad(url);
} 
// main.mjs
import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';

console.log(VERSION); 

使用前面的加载器,运行 node --experimental-loader ./https-loader.mjs ./main.mjs 会在 main.mjs 中的 URL 处按照模块打印当前版本的 CoffeeScript。

With the preceding loader, running node --experimental-loader ./https-loader.mjs ./main.mjs prints the current version of CoffeeScript per the module at the URL in main.mjs.

转译加载器#

可以使用 load 钩子 将 Node.js 无法理解的格式的源代码转换为 JavaScript。

Sources that are in formats Node.js doesn't understand can be converted into JavaScript using the load hook.

这比在运行 Node.js 之前转换源文件的性能要差; 转译器加载器应该只用于开发和测试目的。

This is less performant than transpiling source files before running Node.js; a transpiler loader should only be used for development and testing purposes.

// coffeescript-loader.mjs
import { readFile } from 'node:fs/promises';
import { dirname, extname, resolve as resolvePath } from 'node:path';
import { cwd } from 'node:process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import CoffeeScript from 'coffeescript';

const baseURL = pathToFileURL(`${cwd()}/`).href;

export async function load(url, context, nextLoad) {
  if (extensionsRegex.test(url)) {
    // Now that we patched resolve to let CoffeeScript URLs through, we need to
    // tell Node.js what format such URLs should be interpreted as. Because
    // CoffeeScript transpiles into JavaScript, it should be one of the two
    // JavaScript formats: 'commonjs' or 'module'.

    // CoffeeScript files can be either CommonJS or ES modules, so we want any
    // CoffeeScript file to be treated by Node.js the same as a .js file at the
    // same location. To determine how Node.js would interpret an arbitrary .js
    // file, search up the file system for the nearest parent package.json file
    // and read its "type" field.
    const format = await getPackageType(url);
    // When a hook returns a format of 'commonjs', `source` is ignored.
    // To handle CommonJS files, a handler needs to be registered with
    // `require.extensions` in order to process the files with the CommonJS
    // loader. Avoiding the need for a separate CommonJS handler is a future
    // enhancement planned for ES module loaders.
    if (format === 'commonjs') {
      return {
        format,
        shortCircuit: true,
      };
    }

    const { source: rawSource } = await nextLoad(url, { ...context, format });
    // This hook converts CoffeeScript source code into JavaScript source code
    // for all imported CoffeeScript files.
    const transformedSource = coffeeCompile(rawSource.toString(), url);

    return {
      format,
      shortCircuit: true,
      source: transformedSource,
    };
  }

  // Let Node.js handle all other URLs.
  return nextLoad(url);
}

async function getPackageType(url) {
  // `url` is only a file path during the first iteration when passed the
  // resolved url from the load() hook
  // an actual file path from load() will contain a file extension as it's
  // required by the spec
  // this simple truthy check for whether `url` contains a file extension will
  // work for most projects but does not cover some edge-cases (such as
  // extensionless files or a url ending in a trailing space)
  const isFilePath = !!extname(url);
  // If it is a file path, get the directory it's in
  const dir = isFilePath ?
    dirname(fileURLToPath(url)) :
    url;
  // Compose a file path to a package.json in the same directory,
  // which may or may not exist
  const packagePath = resolvePath(dir, 'package.json');
  // Try to read the possibly nonexistent package.json
  const type = await readFile(packagePath, { encoding: 'utf8' })
    .then((filestring) => JSON.parse(filestring).type)
    .catch((err) => {
      if (err?.code !== 'ENOENT') console.error(err);
    });
  // Ff package.json existed and contained a `type` field with a value, voila
  if (type) return type;
  // Otherwise, (if not at the root) continue checking the next directory up
  // If at the root, stop and return false
  return dir.length > 1 && getPackageType(resolvePath(dir, '..'));
} 
# main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'

import { version } from 'node:process'
console.log "Brought to you by Node.js version #{version}" 
# scream.coffee
export scream = (str) -> str.toUpperCase() 

使用前面的加载器,运行 node --experimental-loader ./coffeescript-loader.mjs main.coffee 会导致 main.coffee 在其源代码从磁盘加载之后但在 Node.js 执行之前被转换为 JavaScript; 对于通过任何加载文件的 import 语句引用的任何 .coffee.litcoffee.coffee.md 文件,依此类推。

With the preceding loader, running node --experimental-loader ./coffeescript-loader.mjs main.coffee causes main.coffee to be turned into JavaScript after its source code is loaded from disk but before Node.js executes it; and so on for any .coffee, .litcoffee or .coffee.md files referenced via import statements of any loaded file.

"导入映射" 加载器#

前两个加载器定义了 load 钩子。 这是一个通过 resolve 钩子完成工作的加载器示例。 此加载程序读取一个 import-map.json 文件,该文件指定要覆盖到另一个 URL 的说明符(这是 "导入映射" 规范的一小部分的非常简单的实现)。

The previous two loaders defined load hooks. This is an example of a loader that does its work via the resolve hook. This loader reads an import-map.json file that specifies which specifiers to override to another URL (this is a very simplistic implemenation of a small subset of the "import maps" specification).

// import-map-loader.js
import fs from 'node:fs/promises';

const { imports } = JSON.parse(await fs.readFile('import-map.json'));

export async function resolve(specifier, context, nextResolve) {
  if (Object.hasOwn(imports, specifier)) {
    return nextResolve(imports[specifier], context);
  }

  return nextResolve(specifier, context);
} 

假设我们有这些文件:

Let's assume we have these files:

// main.js
import 'a-module'; 
// import-map.json
{
  "imports": {
    "a-module": "./some-module.js"
  }
} 
// some-module.js
console.log('some module!'); 

如果运行 node --experimental-loader ./import-map-loader.js main.js,输出将为 some module!

If you run node --experimental-loader ./import-map-loader.js main.js the output will be some module!.

解析和加载算法#

特性#

默认解析器具有以下属性:

The default resolver has the following properties:

  • ES 模块使用的基于 FileURL 的解析
  • 相对和绝对的网址解析
  • 没有默认的扩展名
  • 没有主文件夹
  • 通过 node_modules 进行裸说明符包解析查找
  • 不会在未知扩展或协议上失败
  • 可以选择向加载阶段提供格式提示

默认加载器具有以下属性

The default loader has the following properties

  • 支持通过 node: URL 加载内置模块
  • 支持通过 data: URL 加载 "inline" 模块
  • 支持 file: 模块加载
  • 在任何其他 URL 协议上失败
  • 加载 file: 的未知扩展失败(仅支持 .cjs.js.mjs

解析算法#

加载 ES 模块说明符的算法通过下面的 ESM\RESOLVE 方法给出。 它返回相对于 parentURL 的模块说明符的解析 URL。

The algorithm to load an ES module specifier is given through the ESM_RESOLVE method below. It returns the resolved URL for a module specifier relative to a parentURL.

解析算法确定模块加载的完整解析 URL 及其建议的模块格式。 解析算法不确定是否可以加载解析的 URL 协议,或者是否允许文件扩展名,而是在加载阶段由 Node.js 应用这些验证(例如,如果它被要求加载具有 不是 file:data:node: 的协议,或者如果启用了 --experimental-network-imports,则为 https:)。

The resolution algorithm determines the full resolved URL for a module load, along with its suggested module format. The resolution algorithm does not determine whether the resolved URL protocol can be loaded, or whether the file extensions are permitted, instead these validations are applied by Node.js during the load phase (for example, if it was asked to load a URL that has a protocol that is not file:, data:, node:, or if --experimental-network-imports is enabled, https:).

该算法还尝试根据扩展名确定文件的格式(参见下面的 ESM_FILE_FORMAT 算法)。 如果它不识别文件扩展名(例如,如果它不是 .mjs.cjs.json),则返回 undefined 格式,这将在加载阶段抛出。

The algorithm also tries to determine the format of the file based on the extension (see ESM_FILE_FORMAT algorithm below). If it does not recognize the file extension (eg if it is not .mjs, .cjs, or .json), then a format of undefined is returned, which will throw during the load phase.

确定已解析 URL 的模块格式的算法由 ESM\FILE\FORMAT 提供,它返回任何文件的唯一模块格式。 "module" 格式为 ECMAScript 模块返回,而 "commonjs" 格式用于指示通过旧版 CommonJS 加载器加载。 可以在未来的更新中扩展其他格式,例如 "addon"。

The algorithm to determine the module format of a resolved URL is provided by ESM_FILE_FORMAT, which returns the unique module format for any file. The "module" format is returned for an ECMAScript Module, while the "commonjs" format is used to indicate loading through the legacy CommonJS loader. Additional formats such as "addon" can be extended in future updates.

在以下算法中,除非另有说明,否则所有子程序错误都将作为这些顶层程序的错误传播。

In the following algorithms, all subroutine errors are propagated as errors of these top-level routines unless stated otherwise.

defaultConditions 是条件环境名称数组,["node", "import"]

defaultConditions is the conditional environment name array, ["node", "import"].

解析器可能会抛出以下错误:

The resolver can throw the following errors:

  • 无效的模块说明符: 模块说明符是无效的 URL、包名称或包的子路径说明符。
  • 无效的包配置: package.json 配置无效或包含无效配置。
  • 无效的包目标: 包导出或导入为包定义了一个目标模块,该模块是无效类型或字符串目标。
  • 未导出的包路径: 包导出不为给定模块定义或允许包中的目标子路径。
  • 包导入未定义: 包导入不定义说明符。
  • 未找到模块: 请求的包或模块不存在。
  • 不支持的目录导入: 解析的路径对应于一个目录,该目录不是模块导入的受支持目标。

解析算法规范#

ESM_RESOLVE(specifier, parentURL)

  1. 让解决为 undefined
  2. 如果说明符是有效的 URL,则 1。 将 resolved 设置为将说明符解析和重新序列化为 URL 的结果。
  3. 否则,如果说明符以 "/"、"./" 或 "../" 开头,则为 1。 将 resolved 设置为说明符相对于 parentURL 的 URL 解析。
  4. 否则,如果说明符以 "#" 开头,则为 1。 将 resolved 设置为 PACKAGE\IMPORTS\RESOLVE(specifier, parentURL, defaultConditions) 的结果。
  5. 否则,1。 注意: 说明符现在是一个裸说明符。 2. Set 解析了 PACKAGE\RESOLVE(specifier, parentURL) 的结果。
  6. 让格式为 undefined
  7. 如果解析为 "file:" URL,则为 1。 如果解析包含 "/" 或 "\"(分别为 "%2F" 和 "%5C")的任何百分比编码,则 1。 抛出无效的模块说明符错误。 2. 如果解析的文件是目录,则 1。 引发不支持的目录导入错误。 3. 如果已解决的文件不存在,则 1。 抛出模块未找到错误。 4. 设置 resolved 为 resolved 的真实路径,保持相同的 URL querystring 和 fragment 组件。 5. 将格式设置为 ESM\FILE\FORMAT(已解决)的结果。
  8. 否则,1。 设置格式与解析的 URL 关联的内容类型的模块格式。
  9. 返回格式并解析到加载阶段

PACKAGE_RESOLVE(packageSpecifier, parentURL)

  1. 让 packageName 为 undefined
  2. 如果 packageSpecifier 是空字符串,则为 1。 抛出无效的模块说明符错误。
  3. 如果 packageSpecifier 是 Node.js 内置模块名称,则 1。 返回与 packageSpecifier 连接的字符串 "node:"。
  4. 如果 packageSpecifier 不是以 "@" 开头,则为 1。 将 packageName 设置为 packageSpecifier 的子字符串,直到第一个 "/" 分隔符或字符串的结尾。
  5. 否则,1。 如果 packageSpecifier 不包含 "/" 分隔符,则为 1。 抛出无效的模块说明符错误。 2. 将 packageName 设置为 packageSpecifier 的子字符串,直到第二个 "/" 分隔符或字符串的末尾。
  6. 如果 packageName 以 "." 开头或包含 "\" 或 "%",则为 1。 抛出无效的模块说明符错误。
  7. 让 packageSubpath "." 与 packageSpecifier 的子字符串从 packageName 长度的位置连接起来。
  8. 如果 packageSubpath 以 "/" 结尾,则为 1。 抛出无效的模块说明符错误。
  9. 设 selfUrl 为 PACKAGE\SELF\RESOLVE(packageName, packageSubpath, parentURL) 的结果。
  10. 如果 selfUrl 不是 undefined,则返回 selfUrl。 11. 虽然 parentURL 不是文件系统根,但 1. 令 packageURL 为 "node_modules/" 的 URL 解析与 packageSpecifier 连接,相对于 parentURL。 2. 将 parentURL 设置为 parentURL 的父文件夹 URL。 3. 如果 packageURL 中的文件夹不存在,则 1。 继续下一个循环迭代。 4. 设 pjson 为 READ\PACKAGE\JSON(packageURL) 的结果。 5. 如果 pjson 不是 null 并且 pjson._exports 不是 nullundefined,则 1。 返回 PACKAGE\EXPORTS\RESOLVE(packageURL, packageSubpath, pjson.exports, defaultConditions) 的结果。 6. 否则,如果 packageSubpath 等于 ".",则为 1。 如果 pjson.main 是一个字符串,那么 1。 返回 packageURL 中 main 的 URL 解析。 7. 否则,1。 返回 packageURL 中 packageSubpath 的 URL 解析。 12. 抛出模块未找到错误。

PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)

  1. 令 packageURL 为 LOOKUP\PACKAGE\SCOPE(parentURL) 的结果。
  2. 如果 packageURL 是 null,那么 1。 返回 undefined
  3. 设 pjson 为 READ\PACKAGE\JSON(packageURL) 的结果。
  4. 如果 pjson 是 null 或者如果 pjson._exports 是 nullundefined,那么 1。 返回 undefined
  5. 如果 pjson.name 等于 packageName,则为 1。 返回 PACKAGE\EXPORTS\RESOLVE(packageURL, packageSubpath, pjson.exports, defaultConditions) 的结果。
  6. 否则,返回 undefined

PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)

  1. 如果 exports 是一个对象,其键值以 "." 开头,键值不以 "." 开头,则抛出无效包配置错误。
  2. 如果子路径等于 ".",则为 1。 让 mainExport 为 undefined。 2. 如果 exports 是字符串或数组,或不包含以 "." 开头的键的对象,则为 1。 将 mainExport 设置为导出。 3. 否则,如果 exports 是一个包含 "." 属性的对象,则为 1。 将 mainExport 设置为 exports["."]。 4. 如果 mainExport 不是 undefined,则为 1。 让 resolved 成为 PACKAGE\TARGET\RESOLVE(packageURL、mainExport、nullfalse、条件)的结果。 2. 如果已解决不是 nullundefined,则返回已解决。
  3. 否则,如果 exports 是一个 Object 并且 exports 的所有键都以 "." 开头,则为 1。 令 matchKey 为与子路径连接的字符串 "./"。 2. 让 resolved 成为 PACKAGE\IMPORTS\EXPORTS\RESOLVE(matchKey、exports、packageURL、false、conditions)的结果。 3. 如果已解决不是 nullundefined,则返回已解决。
  4. 抛出包路径未导出错误。

PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)

  1. 断言: 说明符以 "#" 开头。
  2. 如果说明符正好等于 "#" 或以 "#/" 开头,则为 1。 抛出无效的模块说明符错误。
  3. 令 packageURL 为 LOOKUP\PACKAGE\SCOPE(parentURL) 的结果。
  4. 如果 packageURL 不是 null,则为 1。 设 pjson 为 READ\PACKAGE\JSON(packageURL) 的结果。 2. 如果 pjson.imports 是一个非空对象,那么 1。 让 resolved 成为 PACKAGE\IMPORTS\EXPORTS\RESOLVE(说明符、pjson.imports、packageURL、true、条件)的结果。 2. 如果已解决不是 nullundefined,则返回已解决。
  5. 抛出包导入未定义错误。

PACKAGE\IMPORTS\EXPORTS\RESOLVE(matchKey, matchObj, packageURL, isImports, 条件)

PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL, isImports, conditions)

  1. 如果 matchKey 是 matchObj 的一个键,且不包含 "*",则为 1。 设 target 为 matchObj[matchKey] 的值。 2. 返回 PACKAGE\TARGET\RESOLVE(packageURL, target, null, isImports, conditions) 的结果。
  2. 令 expansionKeys 为仅包含单个 "*" 的 matchObj 的键列表,由按特异性降序排列的排序函数 PATTERN\KEY\COMPARE 排序。
  3. 对于 expansionKeys 中的每个键 expansionKey,执行 1。 设 patternBase 是 expansionKey 的子串,但不包括第一个 "*" 字符。 2. 如果 matchKey 以 patternBase 开头但不等于 patternBase,则为 1。 设 patternTrailer 是第一个 "*" 字符后索引中 expansionKey 的子串。 2. 如果 patternTrailer 的长度为零,或者如果 matchKey 以 patternTrailer 结尾且 matchKey 的长度大于或等于 expansionKey 的长度,则为 1。 设 target 为 matchObj[expansionKey] 的值。 2. 令 patternMatch 为 matchKey 的子字符串,从 patternBase 长度的索引开始,直到 matchKey 的长度减去 patternTrailer 的长度。 3. 返回 PACKAGE\TARGET\RESOLVE(packageURL, target, patternMatch, isImports, conditions) 的结果。
  4. 返回 null

PATTERN_KEY_COMPARE(keyA, keyB)

  1. 断言: keyA 以 "/" 结尾或仅包含一个 "*"。
  2. 断言: keyB 以 "/" 结尾或仅包含一个 "*"。
  3. 令 baseLengthA 为 "*" 在 keyA 中的索引加一,如果 keyA 包含 "*",否则为 keyA 的长度。
  4. 令 baseLengthB 为 "*" 在 keyB 中的索引加一,如果 keyB 包含 "*",否则为 keyB 的长度。
  5. 如果 baseLengthA 大于 baseLengthB,则返回 -1。
  6. 如果 baseLengthB 大于 baseLengthA,则返回 1。
  7. 如果 keyA 不包含 "*",则返回 1。
  8. 如果 keyB 不包含 "*",则返回 -1。
  9. 如果 keyA 的长度大于 keyB 的长度,返回-1。
  10. 如果 keyB 的长度大于 keyA 的长度,则返回 1。 11. 返回 0。

PACKAGE\TARGET\RESOLVE(packageURL、目标、模式匹配、isImports、条件)

PACKAGE_TARGET_RESOLVE(packageURL, target, patternMatch, isImports, conditions)

  1. 如果目标是字符串,则为 1。 如果目标不以 "./" 开头,则为 1。 如果 isImports 是 false,或者如果 target 以 "../" 或 "/" 开头,或者如果 target 是一个有效的 URL,那么 1。 抛出一个无效的包目标错误。 2. 如果 patternMatch 是字符串,则为 1。 返回 PACKAGE\RESOLVE(将 "*" 的每个实例替换为 patternMatch、packageURL + "/" 的目标)。 3. 返回 PACKAGE\RESOLVE(目标,packageURL + "/")。 2. 如果 "/" 或 "\" 上的目标拆分在第一个 "." 段之后包含任何 ""、"."、".." 或 "node_modules" 段,不区分大小写并包括百分比编码变体,则抛出无效包目标错误。 3. 令 resolvedTarget 为 packageURL 和 target 串联的 URL 解析。 4. 断言: solvedTarget 包含在 packageURL 中。 5. 如果 patternMatch 为 null,则为 1。 返回已解决的目标。 6. 如果在 "/" 或 "\" 上拆分的 patternMatch 包含任何 ""、"."、".." 或 "node_modules" 段,不区分大小写并包括百分比编码变体,则抛出无效模块说明符错误。 7. 返回 resolvedTarget 的 URL 解析,其中 "*" 的每个实例都替换为 patternMatch。
  2. 否则,如果目标是非空对象,则为 1。 如果导出包含任何索引属性键,如 ECMA-262 6.1.7 数组索引 中所定义,则抛出无效包配置错误。 2. 对于目标的每个属性 p,对象插入顺序为 1。 如果 p 等于 "default" 或条件包含 p 的条目,则 1。 设 targetValue 为 target 中 p 属性的值。 2. 让 resolved 成为 PACKAGE\TARGET\RESOLVE(packageURL、targetValue、patternMatch、isImports、conditions)的结果。 3. 如果 resolved 等于 undefined,继续循环。 4. 返回解决。 3. 返回 undefined
  3. 否则,如果目标是数组,则为 1。 如果 _target.length 为零,则返回 null。 2. 对于 target 中的每个项目 targetValue,执行 1。 让 resolved 成为 PACKAGE\TARGET\RESOLVE(packageURL, targetValue, patternMatch, isImports, conditions) 的结果,在出现任何 Invalid Package Target 错误时继续循环。 2. 如果解析为 undefined,则继续循环。 3. 返回解决。 3. 返回或抛出最后一个后备解决方案 null 返回或错误。
  4. 否则,如果目标为空,则返回 null
  5. 否则抛出一个 Invalid Package Target 错误。

ESM_FILE_FORMAT(url)

  1. 断言: url 对应于现有文件。
  2. 如果 url 以 ".mjs" 结尾,则为 1。 返回 "module"。
  3. 如果 url 以 ".cjs" 结尾,则为 1。 返回 "commonjs"。
  4. 如果 url 以 ".json" 结尾,则为 1。 返回 "json"。
  5. 设 packageURL 为 LOOKUP\PACKAGE\SCOPE(url) 的结果。
  6. 设 pjson 为 READ\PACKAGE\JSON(packageURL) 的结果。
  7. 如果是 pjson?.type 存在并且是 "module",然后是 1。 如果 url 以 ".js" 结尾,则为 1。 返回 "module"。 2. 返回 undefined
  8. 否则,1。 返回 undefined

LOOKUP_PACKAGE_SCOPE(url)

  1. 让 scopeURL 为 url。
  2. 虽然 scopeURL 不是文件系统根目录,但 1. 将 scopeURL 设置为 scopeURL 的父 URL。 2. 如果 scopeURL 以 "node_modules" 路径段结束,则返回 null。 3. 设 pjsonURL 为 scopeURL 中 "package.json" 的解析。 4. 如果 pjsonURL 的文件存在,则 1。 返回范围 URL。
  3. 返回 null

READ_PACKAGE_JSON(packageURL)

  1. 设 pjsonURL 为 packageURL 中 "package.json" 的解析。
  2. 如果 pjsonURL 处的文件不存在,则 1。 返回 null
  3. 如果 packageURL 中的文件未解析为有效的 JSON,则 1。 抛出一个无效的包配置错误。
  4. 在 pjsonURL 返回文件的已解析 JSON 源。

自定义 ESM 说明符解析算法#

稳定性: 1 - 实验

不要依赖这个标志。 我们计划在 加载器 API 发展到可以通过自定义加载程序实现等效功能的程度后将其删除。

当前说明符解析不支持 CommonJS 加载器的所有默认行为。 行为差异之一是文件扩展名的自动解析以及导入具有索引文件的目录的能力。

The current specifier resolution does not support all default behavior of the CommonJS loader. One of the behavior differences is automatic resolution of file extensions and the ability to import directories that have an index file.

--experimental-specifier-resolution=[mode] 标志可用于自定义扩展解析算法。 默认模式是 explicit,它需要向加载程序提供模块的完整路径。 要启用自动扩展解析并从包含索引文件的目录导入,请使用 node 模式。

The --experimental-specifier-resolution=[mode] flag can be used to customize the extension resolution algorithm. The default mode is explicit, which requires the full path to a module be provided to the loader. To enable the automatic extension resolution and importing from directories that include an index file use the node mode.

$ node index.mjs
success!
$ node index # Failure!
Error: Cannot find module
$ node --experimental-specifier-resolution=node index
success!