Skip to content

Commit e1eb099

Browse files
authored
fix: concatenated require() in require.ensure callback or computed request (#21907)
1 parent 8d1ab53 commit e1eb099

9 files changed

Lines changed: 103 additions & 70 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Fix concatenated `require()` in a `require.ensure` callback or a computed request.

‎lib/ConcatenationScope.js‎

Lines changed: 0 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ const {
1919
* ExportName as Ids
2020
* } from "./optimize/ConcatenatedModule"
2121
*/
22-
/** @import { Range } from "./javascript/JavascriptParser" */
2322

2423
/** @typedef {{ start: number, end: number, name: string }} ModuleReferenceMatch */
2524

@@ -76,10 +75,6 @@ class ConcatenationScope {
7675
this.usedNames = usedNames;
7776
/** @type {Map<Module, ModuleInfo>} */
7877
this._modulesMap = modulesMap;
79-
// written and read by dependency templates within a single code
80-
// generation pass, never across passes
81-
/** @type {Range[] | undefined} */
82-
this._replacedRequireRanges = undefined;
8378
}
8479

8580
/**
@@ -121,33 +116,6 @@ class ConcatenationScope {
121116
return this._currentModule.wrapped;
122117
}
123118

124-
/**
125-
* Records a `require(...)` call that was replaced as a whole by a
126-
* concatenation reference, so nothing else rewrites a range inside it.
127-
* @param {Range} range source range of the replaced call
128-
*/
129-
registerReplacedRequire(range) {
130-
if (this._replacedRequireRanges === undefined) {
131-
this._replacedRequireRanges = [];
132-
}
133-
this._replacedRequireRanges.push(range);
134-
}
135-
136-
/**
137-
* Checks whether an offset sits inside an already-replaced `require(...)` call.
138-
* Containment, not exact match: `new require(...)` is replaced from `new`.
139-
* @param {number} start start offset to test
140-
* @returns {boolean} true, when the offset was replaced already
141-
*/
142-
isInsideReplacedRequire(start) {
143-
const ranges = this._replacedRequireRanges;
144-
if (ranges === undefined) return false;
145-
for (const [rangeStart, rangeEnd] of ranges) {
146-
if (start >= rangeStart && start < rangeEnd) return true;
147-
}
148-
return false;
149-
}
150-
151119
/**
152120
* Records the symbol that should be used when the current module exports a
153121
* named binding.

‎lib/dependencies/CommonJsRequireDependency.js‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const HarmonyImportGuard = require("./HarmonyImportGuard");
2020
const ModuleDependency = require("./ModuleDependency");
2121

2222
/** @import { ReplaceSource } from "webpack-sources" */
23+
/** @import ConcatenationScope from "../ConcatenationScope" */
2324
/**
2425
* @import {
2526
* GetConditionFn,
@@ -30,6 +31,7 @@ const ModuleDependency = require("./ModuleDependency");
3031
/** @import { DependencyTemplateContext } from "../DependencyTemplate" */
3132
/** @import Module from "../Module" */
3233
/** @import ModuleGraph from "../ModuleGraph" */
34+
/** @import ModuleGraphConnection from "../ModuleGraphConnection" */
3335
/** @import { Range } from "../javascript/JavascriptParser" */
3436
/** @import { UsedByExports } from "../optimize/InnerGraph" */
3537
/** @import { RuntimeSpec } from "../util/runtime" */
@@ -200,6 +202,19 @@ class CommonJsRequireDependency extends ModuleDependency {
200202
return concatenateCommonJsModules && this._canConcatenate;
201203
}
202204

205+
/**
206+
* @param {ModuleGraphConnection} connection the active connection of this dependency
207+
* @param {ConcatenationScope} concatenationScope the concatenation scope
208+
* @returns {boolean} true when the call becomes a module reference
209+
*/
210+
rendersAsConcatenatedReference(connection, concatenationScope) {
211+
return (
212+
this._canConcatenate &&
213+
this.valueRange !== undefined &&
214+
concatenationScope.isModuleInScope(connection.module)
215+
);
216+
}
217+
203218
/**
204219
* Serializes this instance into the provided serializer context.
205220
* @param {ObjectSerializerContext} context context
@@ -278,9 +293,9 @@ CommonJsRequireDependency.Template = class CommonJsRequireDependencyTemplate ext
278293
if (
279294
connection &&
280295
concatenationScope !== undefined &&
281-
dep.valueRange !== undefined &&
282-
concatenationScope.isModuleInScope(connection.module)
296+
dep.rendersAsConcatenatedReference(connection, concatenationScope)
283297
) {
298+
const valueRange = /** @type {Range} */ (dep.valueRange);
284299
let content = concatenationScope.createModuleReference(
285300
connection.module,
286301
{
@@ -300,8 +315,7 @@ CommonJsRequireDependency.Template = class CommonJsRequireDependencyTemplate ext
300315
);
301316
content = `${RuntimeGlobals.constructRequire}(${content})`;
302317
}
303-
source.replace(dep.valueRange[0], dep.valueRange[1] - 1, content);
304-
concatenationScope.registerReplacedRequire(dep.valueRange);
318+
source.replace(valueRange[0], valueRange[1] - 1, content);
305319
return;
306320
}
307321
const importedModule = /** @type {Module} */ (moduleGraph.getModule(dep));

‎lib/dependencies/RequireHeaderDependency.js‎

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -76,30 +76,29 @@ RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate extends
7676
{ moduleGraph, runtime, runtimeRequirements, concatenationScope }
7777
) {
7878
const dep = /** @type {RequireHeaderDependency} */ (dependency);
79-
80-
// the paired require dependency already replaced the whole call
81-
if (
82-
concatenationScope !== undefined &&
83-
concatenationScope.isInsideReplacedRequire(dep.range[0])
84-
) {
85-
return;
86-
}
87-
8879
const requireDep = dep.requireDependency;
89-
// Skip when the paired call became `0`; dead-branch still needs the header.
9080
if (requireDep) {
9181
const connection = moduleGraph.getConnection(requireDep);
92-
if (
93-
connection &&
94-
!connection.isTargetActive(runtime) &&
95-
requireDep.isEvaluationOnly()
96-
) {
97-
const guards = requireDep.branchGuards;
98-
if (
99-
guards === undefined ||
100-
!HarmonyImportGuard.isDeadByGuards(guards, moduleGraph, runtime)
101-
) {
102-
return;
82+
if (connection) {
83+
if (connection.isTargetActive(runtime)) {
84+
if (
85+
concatenationScope !== undefined &&
86+
requireDep.rendersAsConcatenatedReference(
87+
connection,
88+
concatenationScope
89+
)
90+
) {
91+
return;
92+
}
93+
} else if (requireDep.isEvaluationOnly()) {
94+
// Skip when the paired call became `0`; dead-branch still needs the header.
95+
const guards = requireDep.branchGuards;
96+
if (
97+
guards === undefined ||
98+
!HarmonyImportGuard.isDeadByGuards(guards, moduleGraph, runtime)
99+
) {
100+
return;
101+
}
103102
}
104103
}
105104
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"use strict";
2+
3+
global.__bailoutOrder = (global.__bailoutOrder || []).concat("amd-target");
4+
5+
exports.v = "amd-target";
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
global.__bailoutOrder = (global.__bailoutOrder || []).concat("ensure-target");
2+
3+
export const NAME = "ensure-target";
4+
export default { isDefault: true };
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"use strict";
2+
3+
exports.v = "imported-branch";

‎test/configCases/concatenate-modules/commonjs-require-call-sites/index.js‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// the ESM import gives this entry a concatenation; each require() below decides
22
// whether its target is absorbed into it
33
import { tag } from "./member";
4+
// also a branch of the computed requests below, so it sits in the scope
5+
import importedBranch from "./imported-branch";
46

57
function getLazy() {
68
return require("./lazy").v;
@@ -15,6 +17,12 @@ try {
1517
tryV = "failed";
1618
}
1719
const argM = require(global.__notSet ? "./arg-a" : "./arg-b");
20+
const importedBranchM = require(
21+
global.__notSet ? "./imported-branch" : "./arg-b"
22+
);
23+
const importedBranchTakenM = require(
24+
global.__notSet ? "./arg-b" : "./imported-branch"
25+
);
1826

1927
require("./written-direct").p = "set";
2028
const writtenDirect = require("./written-direct");
@@ -26,7 +34,12 @@ const resolveId = require.resolve("./resolve-target");
2634
const ORDER_AT_LOAD = global.__bailoutOrder.slice();
2735

2836
// no single target for a computed request; require.resolve() cannot concatenate
29-
const BAILED_OUT = ["./arg-a.js", "./arg-b.js", "./resolve-target.js"];
37+
const BAILED_OUT = [
38+
"./arg-a.js",
39+
"./arg-b.js",
40+
"./imported-branch.js",
41+
"./resolve-target.js"
42+
];
3043
// absorbed targets render as wrapped members, so they evaluate at their
3144
// require() instead of at their position in the concatenation
3245
const ABSORBED = [
@@ -62,6 +75,12 @@ it("should resolve a require() with a computed request at runtime", () => {
6275
expect(ORDER_AT_LOAD).not.toContain("arg-a");
6376
});
6477

78+
it("should keep a computed request working when a branch is also imported", () => {
79+
expect(importedBranch.v).toBe("imported-branch");
80+
expect(importedBranchM.v).toBe("arg-b");
81+
expect(importedBranchTakenM.v).toBe("imported-branch");
82+
});
83+
6584
it("should keep a member-assigned require() target writable", () => {
6685
expect(writtenDirect.p).toBe("set");
6786
expect(writtenDirect.v).toBe("written-direct");
@@ -91,6 +110,34 @@ it("should absorb every require() target that can be wrapped", () => {
91110
expect(concatModules[0].modules.map((m) => m.name).sort()).toEqual(ABSORBED);
92111
});
93112

113+
// an async callback moves the require() into a child block, which renders
114+
// after the module's own `require` header
115+
it("should read a whole module object required in a require.ensure callback", () => {
116+
expect(ORDER_AT_LOAD).not.toContain("ensure-target");
117+
return new Promise((resolve) => {
118+
require.ensure(
119+
[],
120+
(require) => {
121+
resolve(require("./ensure-target"));
122+
},
123+
"ensure"
124+
);
125+
}).then((whole) => {
126+
expect(whole.NAME).toBe("ensure-target");
127+
expect(whole.default).toEqual({ isDefault: true });
128+
expect(global.__bailoutOrder).toContain("ensure-target");
129+
});
130+
});
131+
132+
it("should read a whole module object required in an AMD require callback", () =>
133+
new Promise((resolve) => {
134+
require(["./amd-target"], function () {
135+
resolve(require("./amd-target"));
136+
});
137+
}).then((whole) => {
138+
expect(whole.v).toBe("amd-target");
139+
}));
140+
94141
it("should evaluate the absorbed targets at their require(), in source order", () => {
95142
// a bailed-out target is reached through a lazy accessor too, so it keeps its
96143
// source position instead of being hoisted above the concatenation

‎types.d.ts‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4534,18 +4534,6 @@ declare class ConcatenationScope {
45344534
*/
45354535
isWrapped(): boolean;
45364536

4537-
/**
4538-
* Records a `require(...)` call that was replaced as a whole by a
4539-
* concatenation reference, so nothing else rewrites a range inside it.
4540-
*/
4541-
registerReplacedRequire(range: [number, number]): void;
4542-
4543-
/**
4544-
* Checks whether an offset sits inside an already-replaced `require(...)` call.
4545-
* Containment, not exact match: `new require(...)` is replaced from `new`.
4546-
*/
4547-
isInsideReplacedRequire(start: number): boolean;
4548-
45494537
/**
45504538
* Records the symbol that should be used when the current module exports a
45514539
* named binding.

0 commit comments

Comments
 (0)