Skip to content

Commit 22b442c

Browse files
feat: support CommonJS re-export through required binding (#22276)
* feat: recognize a required binding assigned to `exports` as a re-export * fix: keep descriptor attributes and skip async, generator and ignored require-binding re-exports * test: cover CommonJS require-binding re-exports across forms, targets and build modes Only accept a descriptor whose other properties are constant attributes: the rest is kept as written but not walked, so a variable it names was dropped as unused. * perf: read a binding-backed CommonJS re-export off its const binding The re-export reused nothing and printed a fresh module reference. Read the binding instead while its own require renders the module, and test the minimized variant minified. * fix: keep compound and parenthesized CommonJS re-exports valid A compound assignment to exports combines with the current value, so it is no re-export. A binding read through parentheses drops them with what follows. Cover shadowing, ASI, externals, ESM re-exporters and rebuilds flipping the binding. --------- Co-authored-by: alexander-akait <[email protected]>
1 parent 2acd821 commit 22b442c

84 files changed

Lines changed: 1533 additions & 43 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": minor
3+
---
4+
5+
Recognize a required `const` binding assigned to `exports` as a re-export.

‎lib/dependencies/commonjs/CommonJsExportRequireDependency.js‎

Lines changed: 134 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,14 @@ const {
3838
/** @import ModuleGraphConnection from "../../graph/ModuleGraphConnection" */
3939
/** @import { Range } from "../../javascript/JavascriptParser" */
4040
/** @import { RuntimeSpec } from "../../util/runtime" */
41+
/** @import CommonJsRequireDependency from "./CommonJsRequireDependency" */
4142
/**
4243
* @import {
4344
* CommonJSDependencyBaseKeywords
4445
* } from "./CommonJsDependencyHelpers"
4546
*/
46-
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectDeserializerContext<[undefined | boolean, Range, Range | null, CommonJSDependencyBaseKeywords, ExportInfoName[], ExportInfoName[], boolean, boolean]>} ObjectDeserializerContext */
47-
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectSerializerContext<[undefined | boolean, Range, Range | null, CommonJSDependencyBaseKeywords, ExportInfoName[], ExportInfoName[], boolean, boolean]>} ObjectSerializerContext */
47+
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectDeserializerContext<[undefined | boolean, Range, Range | null, CommonJSDependencyBaseKeywords, ExportInfoName[], ExportInfoName[], boolean, boolean, number | null, Range | null, CommonJsRequireDependency | null]>} ObjectDeserializerContext */
48+
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectSerializerContext<[undefined | boolean, Range, Range | null, CommonJSDependencyBaseKeywords, ExportInfoName[], ExportInfoName[], boolean, boolean, number | null, Range | null, CommonJsRequireDependency | null]>} ObjectSerializerContext */
4849

4950
const idsSymbol = /** @type {symbol} */ (
5051
Symbol("CommonJsExportRequireDependency.ids")
@@ -84,6 +85,14 @@ class CommonJsExportRequireDependency extends ModuleDependency {
8485
// (as produced by `Object.defineProperty`) rather than an eager value.
8586
/** @type {boolean} */
8687
this.getter = false;
88+
// start of the `Object.defineProperty` descriptor, kept verbatim but for its value
89+
/** @type {number | null} */
90+
this.descriptorStart = null;
91+
// the `const` binding of the same `require()` the value reads, and its dependency
92+
/** @type {Range | null} */
93+
this.bindingRange = null;
94+
/** @type {CommonJsRequireDependency | null} */
95+
this.bindingDependency = null;
8796
}
8897

8998
get type() {
@@ -241,12 +250,28 @@ class CommonJsExportRequireDependency extends ModuleDependency {
241250
: ids.length === 0
242251
? null
243252
: ids;
253+
254+
// `require()` of a namespace module returns an object carrying `__esModule`
255+
let namespaceMarker = false;
256+
if (
257+
!esmUnwrap &&
258+
ids.length === 0 &&
259+
importedModule &&
260+
importedModule.getExportsType(moduleGraph, false) === "namespace"
261+
) {
262+
const importedExportsInfo = moduleGraph.getExportsInfo(importedModule);
263+
namespaceMarker = !(
264+
importedExportsInfo.otherExportsInfo.provided === false &&
265+
importedExportsInfo.ownedExports[Symbol.iterator]().next().done
266+
);
267+
}
244268
return {
245269
exports: [
246270
{
247271
name,
248272
from,
249273
export: exportChain,
274+
exports: namespaceMarker ? ["__esModule"] : undefined,
250275
// we can't mangle names that are in an empty object
251276
// because one could access the prototype property
252277
// when export isn't set yet
@@ -430,7 +455,10 @@ class CommonJsExportRequireDependency extends ModuleDependency {
430455
.write(this.names)
431456
.write(this.ids)
432457
.write(this.resultUsed)
433-
.write(this.getter);
458+
.write(this.getter)
459+
.write(this.descriptorStart)
460+
.write(this.bindingRange)
461+
.write(this.bindingDependency);
434462
super.serialize(context);
435463
}
436464

@@ -454,7 +482,13 @@ class CommonJsExportRequireDependency extends ModuleDependency {
454482
this.resultUsed = c6.read();
455483
const c7 = c6.rest;
456484
this.getter = c7.read();
457-
super.deserialize(c7.rest);
485+
const c8 = c7.rest;
486+
this.descriptorStart = c8.read();
487+
const c9 = c8.rest;
488+
this.bindingRange = c9.read();
489+
const c10 = c9.rest;
490+
this.bindingDependency = c10.read();
491+
super.deserialize(c10.rest);
458492
}
459493
}
460494

@@ -464,6 +498,52 @@ makeSerializable(CommonJsExportRequireDependency, [
464498
"webpack/lib/dependencies/CommonJsExportRequireDependency"
465499
]);
466500

501+
/**
502+
* Reads the re-exported value off the `const` binding already holding the same exports.
503+
* Only when that binding renders the module, which it doesn't when its own require is inactive.
504+
* @param {CommonJsExportRequireDependency} dep the dependency
505+
* @param {Module | null} importedModule the re-exported module
506+
* @param {ModuleGraph} moduleGraph the module graph
507+
* @param {RuntimeSpec} runtime the runtime
508+
* @param {boolean} used whether the re-export is used, so its value must be read
509+
* @returns {string | undefined} the access to append to the binding, undefined when it can't be read
510+
*/
511+
const getBindingAccess = (dep, importedModule, moduleGraph, runtime, used) => {
512+
if (!dep.bindingRange || !dep.bindingDependency || !importedModule) return;
513+
const connection = moduleGraph.getConnection(dep.bindingDependency);
514+
if (
515+
!connection ||
516+
connection.module !== importedModule ||
517+
!connection.isTargetActive(runtime)
518+
) {
519+
return;
520+
}
521+
const ids = dep.getIds(moduleGraph);
522+
if (ids.length === 0) return "";
523+
// the binding holds the unwrapped value, whose properties aren't tracked
524+
if (isRequireEsmModuleExportsModule(importedModule, moduleGraph)) return;
525+
const usedImported = /** @type {string | string[] | false} */ (
526+
moduleGraph.getExportsInfo(importedModule).getUsedName(ids, runtime)
527+
);
528+
if (usedImported) {
529+
return propertyAccess(/** @type {string[]} */ (usedImported));
530+
}
531+
// an unused re-export of an unused member keeps only the load the binding did
532+
if (!used) return "";
533+
};
534+
535+
/**
536+
* Replaces what follows the binding up to `end` (its member chain, a closing `})`).
537+
* Nothing follows a bare binding, whose access is then empty too.
538+
* @param {ReplaceSource} source the source
539+
* @param {Range} bindingRange range of the binding identifier
540+
* @param {number} end end of the replaced code
541+
* @param {string} content replacement
542+
*/
543+
const replaceAfterBinding = (source, bindingRange, end, content) => {
544+
if (end > bindingRange[1]) source.replace(bindingRange[1], end - 1, content);
545+
};
546+
467547
CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends (
468548
ModuleDependency.Template
469549
) {
@@ -510,6 +590,51 @@ CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependency
510590
);
511591

512592
const importedModule = moduleGraph.getModule(dep);
593+
const bindingAccess = getBindingAccess(
594+
dep,
595+
importedModule,
596+
moduleGraph,
597+
runtime,
598+
Boolean(used)
599+
);
600+
if (bindingAccess !== undefined) {
601+
const bindingRange = /** @type {Range} */ (dep.bindingRange);
602+
if (!used) {
603+
source.replace(
604+
dep.range[0],
605+
bindingRange[0] - 1,
606+
"/* unused reexport */ "
607+
);
608+
replaceAfterBinding(source, bindingRange, dep.range[1], bindingAccess);
609+
return;
610+
}
611+
if (type === "expression") {
612+
source.replace(
613+
dep.range[0],
614+
bindingRange[0] - 1,
615+
`${base}${propertyAccess(/** @type {string[]} */ (used))} = `
616+
);
617+
} else {
618+
source.replace(
619+
dep.range[0],
620+
/** @type {number} */ (dep.descriptorStart) - 1,
621+
`Object.defineProperty(${base}${propertyAccess(
622+
/** @type {string[]} */ (used).slice(0, -1)
623+
)}, ${JSON.stringify(used[used.length - 1])}, `
624+
);
625+
}
626+
let valueEnd = dep.range[1];
627+
if (type !== "expression") {
628+
const valueRange = /** @type {Range} */ (dep.valueRange);
629+
// `(ns).a`: the value opens before the binding; drop that with what follows it
630+
if (valueRange[0] < bindingRange[0]) {
631+
source.replace(valueRange[0], bindingRange[0] - 1, "");
632+
}
633+
valueEnd = valueRange[1];
634+
}
635+
replaceAfterBinding(source, bindingRange, valueEnd, bindingAccess);
636+
return;
637+
}
513638
/** @type {string} */
514639
let requireExpr;
515640
if (
@@ -590,18 +715,16 @@ CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependency
590715
);
591716
return;
592717
}
593-
const descriptor = dep.getter
594-
? "enumerable: true, get: () => ("
595-
: "value: (";
718+
// Only the target and the value change, so the descriptor keeps its
719+
// attributes and the getter its own function.
596720
source.replace(
597721
dep.range[0],
598-
valueRange[0] - 1,
722+
/** @type {number} */ (dep.descriptorStart) - 1,
599723
`Object.defineProperty(${base}${propertyAccess(
600724
/** @type {string[]} */ (used).slice(0, -1)
601-
)}, ${JSON.stringify(used[used.length - 1])}, { ${descriptor}`
725+
)}, ${JSON.stringify(used[used.length - 1])}, `
602726
);
603-
source.replace(valueRange[0], valueRange[1] - 1, requireExpr);
604-
source.replace(valueRange[1], dep.range[1] - 1, ") })");
727+
source.replace(valueRange[0], valueRange[1] - 1, `(${requireExpr})`);
605728
return;
606729
}
607730
default:

0 commit comments

Comments
 (0)