Skip to content

Commit 97965f5

Browse files
giltayarMylesBorins
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 <jan.krems@gmail.com> Reviewed-By: Myles Borins <myles.borins@gmail.com> Reviewed-By: Geoffrey Booth <webmaster@geoffreybooth.com>
1 parent e9f9d07 commit 97965f5

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

doc/api/esm.md

+45
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,51 @@ thrown:
431431
}
432432
```
433433

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

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

0 commit comments

Comments
 (0)