使用名称自引用包
【Self-referencing a package using its name】
在一个包中,可以通过包的名称引用在包的 package.json 的 "exports" 字段中定义的值。例如,假设 package.json 如下:
【Within a package, the values defined in the package's
package.json "exports" field can be referenced via the package's name.
For example, assuming the package.json is:】
// package.json
{
"name": "a-package",
"exports": {
".": "./index.mjs",
"./foo.js": "./foo.js"
}
} 那么该包中的任何模块都可以引用包本身中的导出内容:
【Then any module in that package can reference an export in the package itself:】
// ./a-module.mjs
import { something } from 'a-package'; // Imports "something" from ./index.mjs. 只有在 package.json 中有 "exports" 时才可以使用自引用,并且只允许导入该 "exports"(在 package.json 中)允许的内容。因此,以下代码在使用之前的包时,将会产生运行时错误:
【Self-referencing is available only if package.json has "exports", and
will allow importing only what that "exports" (in the package.json)
allows. So the code below, given the previous package, will generate a runtime
error:】
// ./another-module.mjs
// Imports "another" from ./m.mjs. Fails because
// the "package.json" "exports" field
// does not provide an export named "./m.mjs".
import { another } from 'a-package/m.mjs'; 在使用 require 时,也可以进行自我引用,无论是在 ES 模块中,还是在 CommonJS 模块中。例如,这段代码也可以正常运行:
【Self-referencing is also available when using require, both in an ES module,
and in a CommonJS one. For example, this code will also work:】
// ./a-module.js
const { something } = require('a-package/foo.js'); // Loads from ./foo.js. 最后,自引用也适用于有作用域的包。例如,这段代码也可以正常工作:
【Finally, self-referencing also works with scoped packages. For example, this code will also work:】
// package.json
{
"name": "@my/package",
"exports": "./index.js"
} // ./index.js
module.exports = 42; // ./other.js
console.log(require('@my/package')); $ node other.js
42