Skip to content

Commit e20a6fb

Browse files
committed
feat: recognize a required binding assigned to exports as a re-export
1 parent 7e6cb67 commit e20a6fb

12 files changed

Lines changed: 146 additions & 8 deletions

File tree

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+
Support CJS tree-shaking better by recognizing a required `const` binding assigned to `exports` as a re-export.

‎lib/dependencies/CommonJsExportsParserPlugin.js‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ const { evaluateToString } = require("../javascript/JavascriptParserHelpers");
99
const RuntimeGlobals = require("../runtime/RuntimeGlobals");
1010
const { recordOptimizationBailout } = require("../util/buildDiagnostics");
1111
const formatLocation = require("../util/formatLocation");
12+
const memoize = require("../util/memoize");
1213
const { propertyAccess } = require("../util/property");
1314
const CommonJsExportRequireDependency = require("./CommonJsExportRequireDependency");
1415
const CommonJsExportsDependency = require("./CommonJsExportsDependency");
@@ -21,6 +22,10 @@ const HarmonyExports = require("./HarmonyExports");
2122
const ModuleDecoratorDependency = require("./ModuleDecoratorDependency");
2223
const RuntimeRequirementsDependency = require("./RuntimeRequirementsDependency");
2324

25+
const getRequireBindingTag = memoize(
26+
() => require("./CommonJsImportsParserPlugin").REQUIRE_BINDING_TAG
27+
);
28+
2429
const FUNCTION_PROPERTY_DROP_HEAD =
2530
CommonJsObjectExportDependency.FUNCTION_PROPERTY_DROP_HEAD;
2631

@@ -45,7 +50,6 @@ const FUNCTION_PROPERTY_DROP_HEAD =
4550
*/
4651
/** @import { ExportInfoName } from "../graph/Dependency" */
4752
/** @import { BuildInfo } from "../module/Module" */
48-
/** @import BasicEvaluatedExpression from "../javascript/BasicEvaluatedExpression" */
4953
/**
5054
* @import JavascriptParser, {
5155
* Range,
@@ -63,6 +67,7 @@ const FUNCTION_PROPERTY_DROP_HEAD =
6367
* CommonJsObjectExportKind
6468
* } from "./CommonJsObjectExportDependency"
6569
*/
70+
/** @import { RequireBindingData } from "./CommonJsImportsParserPlugin" */
6671
/**
6772
* @import {
6873
* JavascriptModuleBuildMeta
@@ -131,6 +136,9 @@ const getReexportOfPropertyDescriptor = (expr) => {
131136
(getFn.type === "FunctionExpression" ||
132137
getFn.type === "ArrowFunctionExpression")
133138
) {
139+
// A parameter or the function's own name would shadow a `const` binding the body names.
140+
if (getFn.params.length > 0) return;
141+
if (getFn.type === "FunctionExpression" && getFn.id) return;
134142
// Arrow with expression body: `() => require("./x")`.
135143
if (getFn.body.type !== "BlockStatement") {
136144
return { expr: /** @type {Expression} */ (getFn.body), getter: true };
@@ -181,10 +189,10 @@ const isFalsyLiteral = (expr) => {
181189
};
182190

183191
/**
184-
* Parses require call.
192+
* Parses a `require()` call, or a `const` binding of one, under a static member chain.
185193
* @param {JavascriptParser} parser the parser
186194
* @param {Expression} expr expression
187-
* @returns {{ argument: BasicEvaluatedExpression, ids: ExportInfoName[] } | undefined} parsed call
195+
* @returns {{ request: string, ids: ExportInfoName[] } | undefined} parsed call
188196
*/
189197
const parseRequireCall = (parser, expr) => {
190198
/** @type {ExportInfoName[]} */
@@ -202,6 +210,13 @@ const parseRequireCall = (parser, expr) => {
202210
}
203211
expr = expr.object;
204212
}
213+
if (expr.type === "Identifier") {
214+
const binding =
215+
/** @type {RequireBindingData | undefined} */
216+
(parser.getTagData(expr.name, getRequireBindingTag()));
217+
if (!binding) return;
218+
return { request: binding.request, ids: ids.reverse() };
219+
}
205220
if (expr.type !== "CallExpression" || expr.arguments.length !== 1) return;
206221
const callee = expr.callee;
207222
if (
@@ -213,7 +228,11 @@ const parseRequireCall = (parser, expr) => {
213228
const arg = expr.arguments[0];
214229
if (arg.type === "SpreadElement") return;
215230
const argValue = parser.evaluateExpression(arg);
216-
return { argument: argValue, ids: ids.reverse() };
231+
if (!argValue.isString()) return;
232+
return {
233+
request: /** @type {string} */ (argValue.string),
234+
ids: ids.reverse()
235+
};
217236
};
218237

219238
/**
@@ -472,7 +491,6 @@ class CommonJsExportsParserPlugin {
472491
const requireCall = parseRequireCall(parser, expr.right);
473492
if (
474493
requireCall &&
475-
requireCall.argument.isString() &&
476494
(members.length === 0 || members[0] !== "__esModule")
477495
) {
478496
enableStructuredExports();
@@ -483,7 +501,7 @@ class CommonJsExportsParserPlugin {
483501
null,
484502
base,
485503
members,
486-
/** @type {string} */ (requireCall.argument.string),
504+
requireCall.request,
487505
requireCall.ids,
488506
!parser.isStatementLevelExpression(expr)
489507
);
@@ -674,13 +692,13 @@ class CommonJsExportsParserPlugin {
674692
const reexport = getReexportOfPropertyDescriptor(descArg);
675693
const requireCall =
676694
reexport && parseRequireCall(parser, reexport.expr);
677-
if (reexport && requireCall && requireCall.argument.isString()) {
695+
if (reexport && requireCall) {
678696
const dep = new CommonJsExportRequireDependency(
679697
/** @type {Range} */ (expr.range),
680698
/** @type {Range} */ (reexport.expr.range),
681699
`Object.defineProperty(${exportsArg.identifier})`,
682700
[property],
683-
/** @type {string} */ (requireCall.argument.string),
701+
requireCall.request,
684702
requireCall.ids,
685703
false
686704
);

‎lib/dependencies/CommonJsImportsParserPlugin.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ const getCommentCompilationWarning = memoize(() =>
6565
* member-access references on `NAME` to the `CommonJsRequireDependency`
6666
* created for the `require()` call.
6767
* @typedef {object} RequireBindingData
68+
* @property {string} request request passed to `require()`
6869
* @property {RawReferencedExports | null} referencedExports mutable list, pushed to as `NAME.x.y` accesses are walked; null means the whole namespace is used. Separate from `dep` so a deferred require (walked after accesses on `NAME`) still collects them; becomes the dep's shared list on creation.
6970
* @property {InstanceType<typeof import("./CommonJsRequireDependency")> | null} dep dependency for the `require()` call, null until the `require()` is walked; kept so a later whole-namespace use can null its list directly
7071
*/
@@ -764,6 +765,7 @@ class CommonJsImportsParserPlugin {
764765
if (!requireInfo || requireInfo.name !== "require") return;
765766
/** @type {RequireBindingData} */
766767
const binding = {
768+
request: arg.value,
767769
referencedExports: [],
768770
dep: null
769771
};
@@ -883,5 +885,6 @@ CommonJsImportsParserPlugin.createRequireAsExpressionHandler =
883885
CommonJsImportsParserPlugin.createRequireCacheDependency =
884886
createRequireCacheDependency;
885887
CommonJsImportsParserPlugin.createRequireHandler = createRequireCallHandler;
888+
CommonJsImportsParserPlugin.REQUIRE_BINDING_TAG = REQUIRE_BINDING_TAG;
886889

887890
module.exports = CommonJsImportsParserPlugin;

‎test/cases/cjs-tree-shaking/reexport-require-binding/index.js‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { ns as whole } from "./reexport-whole";
22
import { ns as viaSpecifier } from "./reexport-specifier";
33
import { picked, flag } from "./partial";
4+
import { ns as viaExports, a, lazy } from "./reexport-cjs";
45

56
it("should keep the whole exports object when an `export const` require binding is re-exported (#21135)", () => {
67
expect(whole.a).toBe("a");
@@ -20,3 +21,11 @@ it("should still tree-shake when only specific members of a require binding are
2021
// `b` is never touched, so it is shaken out of the required module.
2122
expect(flag).toEqual(["a", "usedExports"]);
2223
});
24+
25+
it("should tree-shake a require binding assigned to CommonJS exports", () => {
26+
expect(viaExports.a).toBe("a");
27+
expect(a).toBe("a");
28+
expect(lazy.a).toBe("a");
29+
// The binding is re-exported, so only reads through the re-export count.
30+
expect(viaExports.usedExports).toEqual(["a", "usedExports"]);
31+
});
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const ns = require("./module?shadowed");
2+
exports.ns = ns;
3+
Object.defineProperty(exports, "namedGetter", {
4+
get: function ns() {
5+
return ns;
6+
}
7+
});
8+
Object.defineProperty(exports, "paramGetter", {
9+
get(ns = "param") {
10+
return ns;
11+
}
12+
});
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
const ns = require("./module?cjs");
2+
exports.ns = ns;
3+
exports.a = ns.a;
4+
Object.defineProperty(exports, "lazy", { get: () => ns });
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"use strict";
2+
3+
global.__cjs_binding_effect_ran = true;
4+
exports.value = "EFFECT_VALUE_MARKER";
5+
exports.usedExports = __webpack_exports_info__.usedExports;
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { used, part, partA } from "./lib.cjs";
2+
3+
const libSource = () => String(__webpack_modules__["./lib.cjs"]);
4+
5+
it("drops a side-effect-free module whose require binding is only re-exported unused", () => {
6+
expect(used).toBe("used");
7+
expect("./sef.cjs" in __webpack_modules__).toBe(false);
8+
const src = libSource();
9+
expect(src).not.toMatch(/sef\.cjs/);
10+
expect(src).toMatch(/const sef = 0;/);
11+
expect((src.match(/\/\* unused reexport \*\/ 0;/g) || []).length).toBe(4);
12+
});
13+
14+
it("keeps only the exports read through a re-exported require binding", () => {
15+
expect(partA).toBe("a");
16+
expect(part.b).toBe("b");
17+
expect(part.usedExports).toEqual(["a", "b", "usedExports"]);
18+
expect(String(__webpack_modules__["./part.cjs"])).not.toMatch(
19+
/exports\.c\b/
20+
);
21+
});
22+
23+
it("keeps the side effects of a module whose require binding is re-exported unused", () => {
24+
expect(global.__cjs_binding_effect_ran).toBe(true);
25+
delete global.__cjs_binding_effect_ran;
26+
const src = String(__webpack_modules__["./effect.cjs"]);
27+
expect(src).not.toMatch(/exports\.value/);
28+
expect(src).toMatch(/__webpack_unused_export__ = \[\];/);
29+
expect(libSource()).not.toMatch(/exports\.effect/);
30+
});
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
"use strict";
2+
3+
const sef = require("./sef.cjs");
4+
const part = require("./part.cjs");
5+
const effect = require("./effect.cjs");
6+
7+
exports.whole = sef;
8+
exports.member = sef.y;
9+
Object.defineProperty(exports, "viaValue", { enumerable: true, value: sef });
10+
Object.defineProperty(exports, "viaGetter", { enumerable: true, get: () => sef });
11+
12+
exports.part = part;
13+
exports.partA = part.a;
14+
15+
exports.effect = effect;
16+
17+
exports.used = "used";
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
"use strict";
2+
3+
exports.a = "a";
4+
exports.b = "b";
5+
exports.c = "PART_C_MARKER";
6+
exports.usedExports = __webpack_exports_info__.usedExports;

0 commit comments

Comments
 (0)