Skip to content

Commit

Permalink
doc: document self-referencing a package name
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
giltayar authored and MylesBorins committed Mar 9, 2020
1 parent e9f9d07 commit 97965f5
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions doc/api/esm.md
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,51 @@ thrown:
}
```

#### Self-referencing a package using its name

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:

```json
// 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:

```js
// ./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 package above, will generate a runtime error:

```js
// ./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:

```js
// ./a-module.js
const { something } = require('a-package/foo'); // Loads from ./foo.js.
```

### Dual CommonJS/ES Module Packages

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

0 comments on commit 97965f5

Please sign in to comment.