使用名称来引用包
在一个包中,在包的 package.json
"exports"
字段中定义的值可以通过包的名称引用。
例如,假设 package.json
是:
// package.json
{
"name": "a-package",
"exports": {
".": "./main.mjs",
"./foo": "./foo.js"
}
}
然后该包中的任何模块都可以引用包本身中的导出:
// ./a-module.mjs
import { something } from 'a-package'; // 从 ./main.mjs 导入 "something"。
自引用仅在 package.json
具有 "exports"
时可用,并且只允许导入 "exports"
(在 package.json
中)允许的内容。
所以下面的代码,给定前面的包,会产生运行时错误:
// ./another-module.mjs
// 从 ./m.mjs 导入 "another"。
// 失败,因为 "package.json" "exports" 字段
// 不提供名为 "./m.mjs" 的导出。
import { another } from 'a-package/m.mjs';
在 ES 模块和 CommonJS 模块中使用 require
时也可以使用自引用。
例如,这段代码也可以工作:
// ./a-module.js
const { something } = require('a-package/foo'); // 从 ./foo.js 加载。
最后,自引用也适用于作用域包。 例如,这段代码也可以工作:
// package.json
{
"name": "@my/package",
"exports": "./index.js"
}
// ./index.js
module.exports = 42;
// ./other.js
console.log(require('@my/package'));
$ node other.js
42
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": {
".": "./main.mjs",
"./foo": "./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 ./main.mjs.
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';
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'); // 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