File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff 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
436481Prior to the introduction of support for ES modules in Node.js, it was a common
You can’t perform that action at this time.
0 commit comments