diff options
author | Gil Tayar <gil@tayar.org> | 2020-02-07 11:27:55 -0800 |
---|---|---|
committer | Anna Henningsen <anna@addaleax.net> | 2020-03-09 12:36:13 +0100 |
commit | 9dbe6ab2773372bd04c0626826efd7ed845227a8 (patch) | |
tree | f4532289b3ffd592fdd6d9f89fba3cc8030a63f1 /doc/api/esm.md | |
parent | 7bb4f95c1cdf860082a27e2592488c2ba6734c20 (diff) | |
download | node-new-9dbe6ab2773372bd04c0626826efd7ed845227a8.tar.gz |
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: https://github.com/nodejs/node/pull/31680
Reviewed-By: Jan Krems <jan.krems@gmail.com>
Reviewed-By: Myles Borins <myles.borins@gmail.com>
Reviewed-By: Geoffrey Booth <webmaster@geoffreybooth.com>
Diffstat (limited to 'doc/api/esm.md')
-rw-r--r-- | doc/api/esm.md | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/doc/api/esm.md b/doc/api/esm.md index 7abaab87e0..60c0a6f286 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -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 |