Skip to content

Commit 3f1b916

Browse files
giltayarcodebytere
authored andcommitted
doc: document self-referencing a package name
Added a section for "Self-referencing a package using its name" that documents importing a package's own exports (this was missed when adding the feature). PR-URL: #31680 Reviewed-By: Jan Krems <[email protected]> Reviewed-By: Myles Borins <[email protected]> Reviewed-By: Geoffrey Booth <[email protected]>
1 parent 2582083 commit 3f1b916

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: doc/api/esm.md

+45
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,51 @@ thrown:
442442
}
443443
```
444444

445+
#### Self-referencing a package using its name
446+
447+
Within a package, the values defined in the package’s
448+
`package.json` `"exports"` field can be referenced via the package’s name.
449+
For example, assuming the `package.json` is:
450+
451+
```json
452+
// package.json
453+
{
454+
"name": "a-package",
455+
"exports": {
456+
".": "./main.mjs",
457+
"./foo": "./foo.js"
458+
}
459+
}
460+
```
461+
462+
Then any module _in that package_ can reference an export in the package itself:
463+
464+
```js
465+
// ./a-module.mjs
466+
import { something } from 'a-package'; // Imports "something" from ./main.mjs.
467+
```
468+
469+
Self-referencing is available only if `package.json` has `exports`, and will
470+
allow importing only what that `exports` (in the `package.json`) allows.
471+
So the code below, given the package above, will generate a runtime error:
472+
473+
```js
474+
// ./another-module.mjs
475+
476+
// Imports "another" from ./m.mjs. Fails because
477+
// the "package.json" "exports" field
478+
// does not provide an export named "./m.mjs".
479+
import { another } from 'a-package/m.mjs';
480+
```
481+
482+
Self-referencing is also available when using `require`, both in an ES module,
483+
and in a CommonJS one. For example, this code will also work:
484+
485+
```js
486+
// ./a-module.js
487+
const { something } = require('a-package/foo'); // Loads from ./foo.js.
488+
```
489+
445490
### Dual CommonJS/ES Module Packages
446491

447492
Prior to the introduction of support for ES modules in Node.js, it was a common

0 commit comments

Comments
 (0)