术语


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

有三种类型的说明符:

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

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

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

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

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

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

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

There are three types of specifiers:

  • Relative specifiers like './startup.js' or '../config.mjs'. They refer to a path relative to the location of the importing file. The file extension is always necessary for these.

  • Bare specifiers like 'some-package' or 'some-package/shuffle'. They can refer to the main entry point of a package by the package name, or a specific feature module within a package prefixed by the package name as per the examples respectively. Including the file extension is only necessary for packages without an "exports" field.

  • Absolute specifiers like 'file:///opt/nodejs/config.js'. They refer directly and explicitly to a full path.

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

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".

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