子路径模式


【Subpath patterns】

对于导出或导入数量较少的包,我们建议显式列出每个 exports 子路径条目。但对于子路径数量较多的包,这可能会导致 package.json 文件变大并带来维护问题。

【For packages with a small number of exports or imports, we recommend explicitly listing each exports subpath entry. But for packages that have large numbers of subpaths, this might cause package.json bloat and maintenance issues.】

对于这些用例,可以使用子路径导出模式:

【For these use cases, subpath export patterns can be used instead:】

// ./node_modules/es-module-package/package.json
{
  "exports": {
    "./features/*.js": "./src/features/*.js"
  },
  "imports": {
    "#internal/*.js": "./src/internal/*.js"
  }
} 

* 映射仅作为字符串替换语法暴露嵌套子路径。

右边所有的 * 实例都将被此值替换,包括其中包含任何 / 分隔符的情况。

【All instances of * on the right hand side will then be replaced with this value, including if it contains any / separators.】

import featureX from 'es-module-package/features/x.js';
// Loads ./node_modules/es-module-package/src/features/x.js

import featureY from 'es-module-package/features/y/y.js';
// Loads ./node_modules/es-module-package/src/features/y/y.js

import internalZ from '#internal/z.js';
// Loads ./node_modules/es-module-package/src/internal/z.js 

这是一个直接的静态匹配和替换,不对文件扩展名进行任何特殊处理。在映射的两侧都包含 "*.js" 会将暴露的包导出限制为仅 JS 文件。

【This is a direct static matching and replacement without any special handling for file extensions. Including the "*.js" on both sides of the mapping restricts the exposed package exports to only JS files.】

通过导出模式,导出具有静态可枚举性的特性得以保持,因为可以通过将右侧的目标模式视为针对包内文件列表的 ** 通配符来确定包的各个导出。由于在导出目标中禁止使用 node_modules 路径,这种展开仅依赖于包自身的文件。

【The property of exports being statically enumerable is maintained with exports patterns since the individual exports for a package can be determined by treating the right hand side target pattern as a ** glob against the list of files within the package. Because node_modules paths are forbidden in exports targets, this expansion is dependent on only the files of the package itself.】

要从模式中排除私有子文件夹,可以使用 null 目标:

【To exclude private subfolders from patterns, null targets can be used:】

// ./node_modules/es-module-package/package.json
{
  "exports": {
    "./features/*.js": "./src/features/*.js",
    "./features/private-internal/*": null
  }
} 
import featureInternal from 'es-module-package/features/private-internal/m.js';
// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED

import featureX from 'es-module-package/features/x.js';
// Loads ./node_modules/es-module-package/src/features/x.js