From 7e8175e0db061ee246ddb1adb313a8fbc8bac4ed Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Wed, 10 Jun 2020 16:05:16 +0300 Subject: [PATCH 1/2] doc: add conditional export + nested ESM example Such usage was not entirely clear from the doc so adding an example to the dual package section. --- doc/api/esm.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/doc/api/esm.md b/doc/api/esm.md index 38885d7a0b243e..de14dc14a129e9 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -689,6 +689,31 @@ stateless): } ``` +Another variant to also preserve backward-compatibility of `require`ing some +files from the package that were previously available is to combine [Conditional +Exports][] with [Nested conditions][] as follows: + + +```js +// This will allow to: +// `import 'package'` +// `require('package')` +// `require('package/lib/file')` +// while preventing to `import 'package/lib/file.js'`. +{ + "main": "./index.cjs", + "exports": { + ".": { + "import": "./wrapper.mjs", + "require": "./index.cjs" + }, + "./lib": { + "require": "./lib" + } + } +} +``` + ##### Approach #2: Isolate State A `package.json` file can define the separate CommonJS and ES module entry @@ -1807,6 +1832,7 @@ success! [ECMAScript-modules implementation]: https://github.com/nodejs/modules/blob/master/doc/plan-for-new-modules-implementation.md [ECMAScript Top-Level `await` proposal]: https://github.com/tc39/proposal-top-level-await/ [ES Module Integration Proposal for Web Assembly]: https://github.com/webassembly/esm-integration +[Nested conditions]: #esm_nested_conditions [Node.js EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md [Terminology]: #esm_terminology [WHATWG JSON modules specification]: https://html.spec.whatwg.org/#creating-a-json-module-script From 919d76fcc9223691fc052ae95148b7ea5270de3c Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Wed, 10 Jun 2020 19:31:55 +0300 Subject: [PATCH 2/2] fixup! doc: add conditional export + nested ESM example Co-authored-by: Derek Lewis --- doc/api/esm.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/esm.md b/doc/api/esm.md index de14dc14a129e9..d462b190fbfef0 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -694,7 +694,7 @@ files from the package that were previously available is to combine [Conditional Exports][] with [Nested conditions][] as follows: -```js +```json // This will allow to: // `import 'package'` // `require('package')`