解析算法


【Resolution algorithm】

加载 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 应用的(例如,如果请求加载的 URL 具有非 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 提供,它会返回任何文件的唯一模块格式。对于 ECMAScript 模块,会返回 "module" 格式,而 "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 配置无效或包含无效的配置。
  • 无效的包目标: 包的导出或导入定义了一个无效类型或字符串目标的包模块。
  • 包路径未导出: 包导出未定义或不允许在给定模块的包中使用目标子路径。
  • 未定义的包导入: 包导入未定义说明符。
  • 模块未找到:请求的包或模块不存在。
  • 不支持的目录导入:解析的路径对应于一个目录,该目录不是模块导入的支持目标。