@@ -240,20 +240,47 @@ To create an ESM module that should provide an arbitrary value to CommonJS, the
240
240
export default class Point {
241
241
constructor (x , y ) { this .x = x; this .y = y; }
242
242
}
243
+
244
+ // `distance` is lost to CommonJS consumers of this module, unless it's
245
+ // added to `Point` as a static property.
243
246
export function distance (a , b ) { return (b .x - a .x ) ** 2 + (b .y - a .y ) ** 2 ; }
244
247
export const cjsUnwrapDefault = true ;
245
248
```
246
249
247
250
``` 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
251
257
```
252
258
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
+
257
284
258
285
If the module being ` require ()` 'd contains top-level ` await ` , or the module
259
286
graph it ` import ` s contains top-level ` await` ,
0 commit comments