主入口点导出


【Main entry point export】

在编写新软件包时,建议使用 "exports" 字段:

【When writing a new package, it is recommended to use the "exports" field:】

{
  "exports": "./index.js"
} 

当定义了 "exports" 字段时,包的所有子路径都会被封装,导入者将无法再访问。例如,require('pkg/subpath.js') 会抛出 ERR_PACKAGE_PATH_NOT_EXPORTED 错误。

【When the "exports" field is defined, all subpaths of the package are encapsulated and no longer available to importers. For example, require('pkg/subpath.js') throws an ERR_PACKAGE_PATH_NOT_EXPORTED error.】

这种对导出的封装为工具以及在处理包的语义化版本升级时提供了更可靠的包接口保证。这不是一种强封装,因为对包的任何绝对子路径的直接 require,例如 require('/path/to/node_modules/pkg/subpath.js'),仍然会加载 subpath.js

【This encapsulation of exports provides more reliable guarantees about package interfaces for tools and when handling semver upgrades for a package. It is not a strong encapsulation since a direct require of any absolute subpath of the package such as require('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.】

所有目前支持的 Node.js 版本和现代构建工具都支持 "exports" 字段。对于使用较旧版本 Node.js 或相关构建工具的项目,可以通过在 "exports" 字段旁边包含 "main" 字段并指向同一个模块来实现兼容性:

【All currently supported versions of Node.js and modern build tools support the "exports" field. For projects using an older version of Node.js or a related build tool, compatibility can be achieved by including the "main" field alongside "exports" pointing to the same module:】

{
  "main": "./index.js",
  "exports": "./index.js"
}