子路径的导入


除了 "exports" 字段之外,还有一个包 "imports" 字段用于创建仅适用于包本身的导入说明符的私有映射。

"imports" 字段中的条目必须始终以 # 开头,以确保它们与外部包说明符消除歧义。

例如,可以使用导入字段来获得内部模块条件导出的好处:

// package.json
{
  "imports": {
    "#dep": {
      "node": "dep-node-native",
      "default": "./dep-polyfill.js"
    }
  },
  "dependencies": {
    "dep-node-native": "^1.0.0"
  }
}

其中 import '#dep' 没有得到外部包 dep-node-native 的解析(依次包括其导出),而是获取了相对于其他环境中的包的本地文件 ./dep-polyfill.js

"exports" 字段不同,"imports" 字段允许映射到外部包。

导入字段的解析规则与导出字段类似。

In addition to the "exports" field, there is a package "imports" field to create private mappings 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 external package specifiers.

For example, the imports field can be used to gain the benefits of conditional exports for internal modules:

// package.json
{
  "imports": {
    "#dep": {
      "node": "dep-node-native",
      "default": "./dep-polyfill.js"
    }
  },
  "dependencies": {
    "dep-node-native": "^1.0.0"
  }
}

where import '#dep' does not get the resolution of the external package dep-node-native (including its exports in turn), and instead gets the local file ./dep-polyfill.js relative to the package in other environments.

Unlike the "exports" field, the "imports" field permits mapping to external packages.

The resolution rules for the imports field are otherwise analogous to the exports field.