使用名称自引用包


¥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'; 

在 ES 模块和 CommonJS 模块中使用 require 时也可以使用自引用。例如,这段代码也可以工作:

¥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