From 4afabbf416aea4cff688695ae58c0b40103c861c Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Fri, 6 Sep 2024 16:26:54 -0700 Subject: [PATCH] Apply suggestions from code review Co-authored-by: Joyee Cheung --- doc/api/modules.md | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/doc/api/modules.md b/doc/api/modules.md index 8fd942a7bee2e4..00962f9817137c 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -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'); +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`,