主入口的导出
要设置包的主入口点,建议在包的 package.json
文件中同时定义 "exports"
和 "main"
:
{
"main": "./main.js",
"exports": "./main.js"
}
当定义了 "exports"
字段时,则包的所有子路径都被封装,不再提供给导入器。
例如,require('pkg/subpath.js')
抛出 ERR_PACKAGE_PATH_NOT_EXPORTED
错误。
这种导出的封装为工具的包接口以及处理包的语义版本升级提供了更可靠的保证。
这不是强封装,因为直接要求包的任何绝对子路径,例如 require('/path/to/node_modules/pkg/subpath.js')
仍然会加载 subpath.js
。
To set the main entry point for a package, it is advisable to define both
"exports"
and "main"
in the package’s package.json
file:
{
"main": "./main.js",
"exports": "./main.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
.