模块加载器
¥Modules loaders
Node.js 有两个系统用于解析说明符和加载模块。
¥Node.js has two systems for resolving a specifier and loading modules.
有 CommonJS 模块加载器:
¥There is the CommonJS module loader:
-
它是完全同步的。
¥It is fully synchronous.
-
它负责处理
require()
调用。¥It is responsible for handling
require()
calls. -
它是可修补的。
¥It is monkey patchable.
-
它支持 文件夹作为模块。
¥It supports folders as modules.
-
解析说明符时,如果未找到完全匹配项,它将尝试添加扩展名(
.js
、.json
,最后是.node
),然后尝试解析 文件夹作为模块。¥When resolving a specifier, if no exact match is found, it will try to add extensions (
.js
,.json
, and finally.node
) and then attempt to resolve folders as modules. -
它将
.json
视为 JSON 文本文件。¥It treats
.json
as JSON text files. -
.node
文件被解释为加载了process.dlopen()
的编译插件模块。¥
.node
files are interpreted as compiled addon modules loaded withprocess.dlopen()
. -
它将所有缺少
.json
或.node
扩展名的文件视为 JavaScript 文本文件。¥It treats all files that lack
.json
or.node
extensions as JavaScript text files. -
它不能用于加载 ECMAScript 模块(尽管 从 CommonJS 模块加载 ECMASCript 模块 是可能的)。当用于加载不是 ECMAScript 模块的 JavaScript 文本文件时,则它将作为 CommonJS 模块加载。
¥It cannot be used to load ECMAScript modules (although it is possible to load ECMASCript modules from CommonJS modules). When used to load a JavaScript text file that is not an ECMAScript module, it loads it as a CommonJS module.
有 ECMAScript 模块加载器:
¥There is the ECMAScript module loader:
-
它是异步的。
¥It is asynchronous.
-
负责处理
import
语句和import()
表达式。¥It is responsible for handling
import
statements andimport()
expressions. -
它不是猴子可修补的,可以使用 加载器钩子 进行定制。
¥It is not monkey patchable, can be customized using loader hooks.
-
它不支持文件夹作为模块,必须完全指定目录索引(例如
'./startup/index.js'
)。¥It does not support folders as modules, directory indexes (e.g.
'./startup/index.js'
) must be fully specified. -
它不进行扩展名搜索。当说明符是相对或绝对的文件 URL 时,必须提供文件扩展名。
¥It does no extension searching. A file extension must be provided when the specifier is a relative or absolute file URL.
-
它可以加载 JSON 模块,但需要导入断言。
¥It can load JSON modules, but an import assertion is required.
-
它只接受 JavaScript 文本文件的
.js
、.mjs
和.cjs
扩展名。¥It accepts only
.js
,.mjs
, and.cjs
extensions for JavaScript text files. -
它可以用来加载 JavaScript CommonJS 模块。这样的模块通过
cjs-module-lexer
来尝试识别命名的导出,如果可以通过静态分析确定的话是可用的。导入的 CommonJS 模块将其 URL 转换为绝对路径,然后通过 CommonJS 模块加载器加载。¥It can be used to load JavaScript CommonJS modules. Such modules are passed through the
cjs-module-lexer
to try to identify named exports, which are available if they can be determined through static analysis. Imported CommonJS modules have their URLs converted to absolute paths and are then loaded via the CommonJS module loader.