主入口的导出


当编写新包时,建议使用 "exports" 字段:

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

当定义了 "exports" 字段时,则包的所有子路径都被封装,不再提供给导入器。 例如,require('pkg/subpath.js') 抛出 ERR_PACKAGE_PATH_NOT_EXPORTED 错误。

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

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

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

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

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

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.

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.

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