Skip to content

Commit da0e809

Browse files
authored
fix(cjs): disconnect unused side-effect-free reexport requires (#21651)
Deactivate CommonJsExportRequireDependency when a named reexport is unused and either a getter or an eager require of a side-effect-free module, while keeping whole-module assigns and missing targets alive.
1 parent 7288459 commit da0e809

29 files changed

Lines changed: 283 additions & 18 deletions

File tree

‎.changeset/040-drop-unused-cjs-requires.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": patch
33
---
44

5-
Drop unused side-effect-free CommonJS require() calls.
5+
Drop unused side-effect-free CommonJS require() calls and reexports.

‎lib/dependencies/CommonJsExportRequireDependency.js‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const processExportInfo = require("./processExportInfo");
2222

2323
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
2424
/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
25+
/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */
2526
/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
2627
/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
2728
/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */
@@ -31,6 +32,7 @@ const processExportInfo = require("./processExportInfo");
3132
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
3233
/** @typedef {import("../Module")} Module */
3334
/** @typedef {import("../ModuleGraph")} ModuleGraph */
35+
/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
3436
/** @typedef {import("../javascript/JavascriptParser").Range} Range */
3537
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
3638
/** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */
@@ -102,6 +104,31 @@ class CommonJsExportRequireDependency extends ModuleDependency {
102104
return concatenateCommonJsModules;
103105
}
104106

107+
/**
108+
* Returns function to determine if the connection is active.
109+
* @param {ModuleGraph} moduleGraph module graph
110+
* @returns {null | false | GetConditionFn} function to determine if the connection is active
111+
*/
112+
getCondition(moduleGraph) {
113+
// Conservative: keep `module.exports = require(...)` (names empty) active even
114+
// when the parent is evaluation-only and the target is side-effect-free.
115+
if (this.resultUsed || this.names.length === 0) return null;
116+
const names = this.names;
117+
const getter = this.getter;
118+
return (connection, runtime) => {
119+
const parentModule = moduleGraph.getParentModule(this);
120+
if (!parentModule) return true;
121+
const used = moduleGraph
122+
.getExportsInfo(parentModule)
123+
.getUsedName(names, runtime);
124+
if (used !== false) return true;
125+
if (getter) return false;
126+
const refModule = connection.resolvedModule;
127+
if (!refModule) return true;
128+
return refModule.getSideEffectsConnectionState(moduleGraph);
129+
};
130+
}
131+
105132
/**
106133
* Returns the imported id.
107134
* @param {ModuleGraph} moduleGraph the module graph
@@ -459,6 +486,16 @@ CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependency
459486
moduleGraph.getExportsInfo(module).getUsedName(dep.names, runtime)
460487
);
461488

489+
const connection = /** @type {ModuleGraphConnection | undefined} */ (
490+
moduleGraph.getConnection(dep)
491+
);
492+
// Inactive unused reexport: no module id; drop to a no-op.
493+
// Missing connection (e.g. IgnorePlugin) must keep the require so it throws.
494+
if (!used && connection && !connection.isTargetActive(runtime)) {
495+
source.replace(dep.range[0], dep.range[1] - 1, "/* unused reexport */ 0");
496+
return;
497+
}
498+
462499
const [type, base] = handleDependencyBase(
463500
dep.base,
464501
module,
@@ -535,14 +572,12 @@ CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependency
535572
// barrel files (e.g. webpack's own `lib/index.js`).
536573
const valueRange = /** @type {Range} */ (dep.valueRange);
537574
if (!used) {
538-
// A lazy getter never runs `require` until accessed, so an unused
539-
// one can be dropped entirely; an eager value must keep side effects.
575+
// Active unused eager reexport: keep side effects. Unused getters
576+
// are inactive and already replaced with `0` above.
540577
source.replace(
541578
dep.range[0],
542579
dep.range[1] - 1,
543-
dep.getter
544-
? "/* unused reexport */ 0"
545-
: `/* unused reexport */ ${requireExpr}`
580+
`/* unused reexport */ ${requireExpr}`
546581
);
547582
return;
548583
}
Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import { A } from "./a.cjs";
22
import { B } from "./b.cjs";
33

4-
// `fromA`/`fromB` stay unused, so each require references no export while both
5-
// modules are still required and evaluated. Walking them has to be recorded
6-
// separately from any usage flag, or this cycle never reaches a fixpoint and
7-
// the compilation hangs.
8-
it("terminates on cyclic evaluation-only requires between side-effect-free modules", () => {
4+
// Unused cyclic reexports between side-effect-free modules must deactivate
5+
// without hanging, while used exports stay.
6+
it("terminates on cyclic unused reexports between side-effect-free modules", () => {
97
expect(A).toBe(1);
108
expect(B).toBe(2);
119
const src = String(__webpack_modules__["./a.cjs"]);
12-
expect(src).toMatch(/unused reexport/);
10+
expect(src).toMatch(/\/\* unused reexport \*\/ 0/);
1311
});

‎test/configCases/cjs-tree-shaking/side-effect-free-unused-export-require/index.js‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import { NodeSDK } from "./sdk-node.cjs";
22

33
export const sdk = new NodeSDK();
44

5-
// `tracing` is never imported, so the `require("./utility.cjs")` behind it
6-
// references no export while the module is still required and evaluated.
7-
it("keeps a self-referenced export behind an unused cjs re-export", () => {
5+
// `tracing` is never imported; the side-effect-free reexport target is dropped.
6+
it("drops a side-effect-free module behind an unused cjs re-export", () => {
87
expect(sdk).toBeInstanceOf(NodeSDK);
9-
const src = String(__webpack_modules__["./utility.cjs"]);
10-
expect(src).toMatch(/exports\.DEFAULT_LIMIT = 128;/);
11-
expect(src).toMatch(/__webpack_unused_export__ = function getLimit/);
8+
expect("./utility.cjs" in __webpack_modules__).toBe(false);
9+
expect(String(__webpack_modules__["./sdk-node.cjs"])).toMatch(
10+
/\/\* unused reexport \*\/ 0/
11+
);
1212
});
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
"use strict";
2+
3+
global.__cjs_unused_eager_effect_ran = true;
4+
module.exports = "effect";
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { used } from "./lib.cjs";
2+
3+
it("keeps evaluating a side-effectful module behind an unused eager reexport", () => {
4+
expect(used).toBe("used");
5+
expect("./effect.cjs" in __webpack_modules__).toBe(true);
6+
expect(global.__cjs_unused_eager_effect_ran).toBe(true);
7+
delete global.__cjs_unused_eager_effect_ran;
8+
});
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
"use strict";
2+
3+
exports.unused = require("./effect.cjs");
4+
exports.used = "used";
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration} */
4+
module.exports = {
5+
mode: "production",
6+
target: "node",
7+
optimization: {
8+
minimize: false,
9+
moduleIds: "named",
10+
mangleExports: false,
11+
usedExports: true,
12+
sideEffects: true,
13+
concatenateModules: false
14+
}
15+
};
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
"use strict";
2+
3+
global.__cjs_unused_getter_heavy_ran = true;
4+
module.exports = "heavy";
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { used } from "./lib.cjs";
2+
3+
it("drops a module behind an unused getter reexport even with side effects", () => {
4+
expect(used).toBe("used");
5+
expect("./heavy.cjs" in __webpack_modules__).toBe(false);
6+
expect(global.__cjs_unused_getter_heavy_ran).toBe(undefined);
7+
});

0 commit comments

Comments
 (0)