Nodejs 要求模块以“#”开头

Nodejs require module starts with '#'

来自 Nodejs 文档 https://nodejs.org/api/modules.html#all-together

require(X) from module at path Y
1. If X is a core module,
   a. return the core module
   b. STOP
2. If X begins with '/'
   a. set Y to be the filesystem root
3. If X begins with './' or '/' or '../'
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)
   c. THROW "not found"
4. If X begins with '#'
   a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
5. LOAD_PACKAGE_SELF(X, dirname(Y))
6. LOAD_NODE_MODULES(X, dirname(Y))
7. THROW "not found"

4号指的是什么?
模块以 # 开头是什么意思?

LOAD_PACKAGE_IMPORTS(X, DIR)
1. Find the closest package scope SCOPE to DIR.
2. If no scope was found, return.
3. If the SCOPE/package.json "imports" is null or undefined, return.
4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
  ["node", "require"]) defined in the ESM resolver.
5. RESOLVE_ESM_MATCH(MATCH).

这是 LOAD_PACKAGE_IMPORTS 但我觉得它很神秘。

导入说明符开头的字符“#”指的是package.json中定义的imports field

导入字段对于别名文件名或其他仅在包内访问的依赖项很有用。

考虑文档中的示例:

  "imports": {
    "#dep": {
      "node": "dep-node-native",
      "default": "./dep-polyfill.js"
    }
  }

当此包中的模块包含像

这样的导入语句时
import dep from "#def";

这告诉 Node.js 导入包“dep-node-native”;它指示其他构建工具(用于浏览器)使用本地文件“./dep-polyfill.js”。

这在https://nodejs.org/api/packages.html#subpath-imports中有解释:

Subpath imports

Added in: v14.6.0, v12.19.0

In addition to the "exports" field, it is possible to define internal package import maps that only apply to import specifiers from within the package itself.

Entries in the imports field must always start with # to ensure they are disambiguated from package specifiers.

(强调我的)