术语
【Terminology】
import 语句的 specifier 是 from 关键字之后的字符串,例如 import { sep } from 'node:path' 中的 'node:path'。specifier 也用于 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 模块解析与加载算法 处理。所有其他说明符的解析总是仅通过标准相对 网址 解析语义来解决。
【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 模块解析中裸模块名的这些包解析规则的详细信息,请参阅 packages 文档。
【For details on these package resolution rules that apply to bare specifiers in the Node.js module resolution, see the packages documentation.】