Skip to content

Commit 4afabbf

Browse files
Apply suggestions from code review
Co-authored-by: Joyee Cheung <[email protected]>
1 parent 3c24762 commit 4afabbf

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

doc/api/modules.md

+34-7
Original file line numberDiff line numberDiff line change
@@ -240,20 +240,47 @@ To create an ESM module that should provide an arbitrary value to CommonJS, the
240240
export default class Point {
241241
constructor(x, y) { this.x = x; this.y = y; }
242242
}
243+
244+
// `distance` is lost to CommonJS consumers of this module, unless it's
245+
// added to `Point` as a static property.
243246
export function distance(a, b) { return (b.x - a.x) ** 2 + (b.y - a.y) ** 2; }
244247
export const cjsUnwrapDefault = true;
245248
```
246249

247250
```cjs
248-
const point = require('./point.mjs');
249-
console.log(point);
250-
// [class Point]
251+
const Point = require('./point.mjs');
252+
console.log(Point); // [class Point]
253+
254+
// Named exports are lost when cjsUnwrapDefault is used
255+
const { distance } = require('./point.mjs');
256+
console.log(distance); // undefined
251257
```
252258

253-
When using `cjsUnwrapDefault`, no named exports other than the `default` export
254-
will be accessible to CommonJS importers - `distance` is not available for CJS
255-
consumers in the above `require('./point.mjs')`. Instead it should be made a
256-
property of the class (e.g. as a static method).
259+
Notice in the example above, when `cjsUnwrapDefault` is used, named exports will be
260+
lost to CommonJS consumers. To allow CommonJS consumers to continue accessing
261+
named exports, the module can make sure that the default export is an object with the
262+
named exports attached to it as properties. For example with the example above,
263+
`distance` can be attached to the default export, the `Point` class, as a static method.
264+
265+
```mjs
266+
export function distance(a, b) { return (b.x - a.x) ** 2 + (b.y - a.y) ** 2; }
267+
268+
export default class Point {
269+
constructor(x, y) { this.x = x; this.y = y; }
270+
static distance = distance;
271+
}
272+
273+
export const cjsUnwrapDefault = true;
274+
```mjs
275+
276+
```cjs
277+
const Point = require('./point.mjs');
278+
console.log(Point); // [class Point]
279+
280+
const { distance } = require('./point.mjs');
281+
console.log(distance); // [Function: distance]
282+
```cjs
283+
257284
258285
If the module being `require()`'d contains top-level `await`, or the module
259286
graph it `import`s contains top-level `await`,

0 commit comments

Comments
 (0)