Skip to content

Commit

Permalink
Apply suggestions from code review
Browse files Browse the repository at this point in the history
Co-authored-by: Joyee Cheung <joyeec9h3@gmail.com>
  • Loading branch information
guybedford and joyeecheung authored Sep 6, 2024
1 parent 3c24762 commit 4afabbf
Showing 1 changed file with 34 additions and 7 deletions.
41 changes: 34 additions & 7 deletions doc/api/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,20 +240,47 @@ To create an ESM module that should provide an arbitrary value to CommonJS, the
export default class Point {
constructor(x, y) { this.x = x; this.y = y; }
}

// `distance` is lost to CommonJS consumers of this module, unless it's
// added to `Point` as a static property.
export function distance(a, b) { return (b.x - a.x) ** 2 + (b.y - a.y) ** 2; }
export const cjsUnwrapDefault = true;
```

```cjs
const point = require('./point.mjs');
console.log(point);
// [class Point]
const Point = require('./point.mjs');
console.log(Point); // [class Point]

// Named exports are lost when cjsUnwrapDefault is used
const { distance } = require('./point.mjs');

Check failure on line 255 in doc/api/modules.md

View workflow job for this annotation

GitHub Actions / lint-js-and-md

'./point.mjs' require is duplicated
console.log(distance); // undefined
```

When using `cjsUnwrapDefault`, no named exports other than the `default` export
will be accessible to CommonJS importers - `distance` is not available for CJS
consumers in the above `require('./point.mjs')`. Instead it should be made a
property of the class (e.g. as a static method).
Notice in the example above, when `cjsUnwrapDefault` is used, named exports will be
lost to CommonJS consumers. To allow CommonJS consumers to continue accessing
named exports, the module can make sure that the default export is an object with the
named exports attached to it as properties. For example with the example above,
`distance` can be attached to the default export, the `Point` class, as a static method.

```mjs
export function distance(a, b) { return (b.x - a.x) ** 2 + (b.y - a.y) ** 2; }

export default class Point {
constructor(x, y) { this.x = x; this.y = y; }
static distance = distance;
}

export const cjsUnwrapDefault = true;
```mjs
```cjs
const Point = require('./point.mjs');
console.log(Point); // [class Point]

const { distance } = require('./point.mjs');
console.log(distance); // [Function: distance]
```cjs
If the module being `require()`'d contains top-level `await`, or the module
graph it `import`s contains top-level `await`,
Expand Down

0 comments on commit 4afabbf

Please sign in to comment.