Skip to content

Commit c0dd243

Browse files
fix(library): keep the export helpers where a module entry goes to the registry
The module library entry's export definitions are left out of its source and handed over on demand, which only works where the renderer inlines the entry — rendered into the module registry instead, the stashed source is put back and reads the helpers again. The runtime requirements were dropped in both cases, so a chunk whose entry is executed as a factory called `__webpack_require__.d` and `.r` that the runtime no longer defined. Ask what the renderer asks before dropping them: the startup inlines the entry only when no other chunk of the entrypoint loads with it and no module reads it, and a chunk whose runtime lives elsewhere lifts its entry to the top level under the conditions `_getEsmEntryModuleToInline` already states — now a static so the decision can be made before rendering.
1 parent f346060 commit c0dd243

7 files changed

Lines changed: 148 additions & 45 deletions

File tree

‎.changeset/041-module-library-default-expression.md‎

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

5-
Export a module library entry's default expression as its own binding.
5+
Export a module library entry's default expression as its own binding, and keep
6+
the export helpers where the entry is not inlined.

‎lib/javascript/JavascriptModulesPlugin.js‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,10 +1062,8 @@ class JavascriptModulesPlugin {
10621062
// ESM entry chunk whose runtime lives in a separate chunk: inline the
10631063
// single entry module at the top level (instead of the module registry)
10641064
// so its own top-level declarations stay live ESM bindings for consumers.
1065-
const inlinedEntryModule = this._getEsmEntryModuleToInline(
1066-
renderContext,
1067-
allModules
1068-
);
1065+
const inlinedEntryModule =
1066+
JavascriptModulesPlugin._getEsmEntryModuleToInline(renderContext);
10691067
let registryModules = allModules;
10701068
if (inlinedEntryModule) {
10711069
const inlinedEntrySource = this.renderModule(
@@ -1131,18 +1129,20 @@ class JavascriptModulesPlugin {
11311129
* its exports as live ESM bindings. Only a self-contained ESM entry whose
11321130
* top-level declarations can be lifted into the chunk scope qualifies;
11331131
* otherwise `undefined` is returned and the registry path is used.
1134-
* @param {RenderContext} renderContext render context
1135-
* @param {Module[]} allModules all javascript modules of the chunk
1132+
*
1133+
* Static so that a plugin can decide before the chunk is rendered what it may
1134+
* leave out of the inlined entry's source and put back in the registry.
1135+
* @param {Pick<RenderContext, "chunk" | "chunkGraph" | "moduleGraph" | "runtimeTemplate" | "codeGenerationResults">} context chunk, graphs and code generation results
11361136
* @returns {Module | undefined} the entry module to inline, if any
11371137
*/
1138-
_getEsmEntryModuleToInline(renderContext, allModules) {
1138+
static _getEsmEntryModuleToInline(context) {
11391139
const {
11401140
chunk,
11411141
chunkGraph,
11421142
moduleGraph,
11431143
runtimeTemplate,
11441144
codeGenerationResults
1145-
} = renderContext;
1145+
} = context;
11461146

11471147
// Only a single ESM entry whose runtime lives in a separate chunk.
11481148
if (

‎lib/library/ModuleLibraryPlugin.js‎

Lines changed: 66 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,14 @@ const ConcatenatedModule = require("../optimize/ConcatenatedModule");
2020
const { InlinedUsedName } = require("../optimize/InlineExports");
2121
const RuntimeGlobals = require("../runtime/RuntimeGlobals");
2222
const Template = require("../template/Template");
23+
const { someInIterable } = require("../util/IterableHelpers");
2324
const { renameIdentifiers } = require("../util/concatenate");
2425
const {
2526
RESERVED_IDENTIFIER,
2627
SAFE_IDENTIFIER,
2728
propertyAccess
2829
} = require("../util/property");
29-
const { getEntryRuntime } = require("../util/runtime");
30+
const { getEntryRuntime, intersectRuntime } = require("../util/runtime");
3031
const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
3132

3233
/** @import { Source } from "webpack-sources" */
@@ -37,7 +38,6 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
3738
* LibraryExport
3839
* } from "../../declarations/WebpackOptions"
3940
*/
40-
/** @import Chunk from "../graph/Chunk" */
4141
/** @import CodeGenerationResults from "../module/CodeGenerationResults" */
4242
/** @import Compilation from "../Compilation" */
4343
/** @import Compiler from "../Compiler" */
@@ -170,6 +170,7 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin {
170170
compilation.hooks.additionalChunkRuntimeRequirements.tap(
171171
PLUGIN_NAME,
172172
(chunk, set, { chunkGraph, codeGenerationResults }) => {
173+
const { moduleGraph, runtimeTemplate } = compilation;
173174
if (!set.has(RuntimeGlobals.definePropertyGetters)) return;
174175
if (chunkGraph.getNumberOfEntryModules(chunk) !== 1) return;
175176
if (
@@ -184,6 +185,48 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin {
184185
if (javascriptHooks.inlineInRuntimeBailout.isUsed()) return;
185186

186187
const [module] = chunkGraph.getChunkEntryModulesIterable(chunk);
188+
if (chunk.hasRuntime()) {
189+
// The startup inlines the entry only where nothing else loads with
190+
// it: another chunk of the entrypoint delays the execution, and a
191+
// module reading the entry needs it in the registry.
192+
for (const [
193+
,
194+
entrypoint
195+
] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) {
196+
if (entrypoint && entrypoint.chunks.some((c) => c !== chunk)) {
197+
return;
198+
}
199+
}
200+
if (
201+
someInIterable(
202+
moduleGraph.getIncomingConnectionsByOriginModule(module),
203+
([originModule, connections]) =>
204+
originModule &&
205+
originModule !== module &&
206+
connections.some((c) => c.isTargetActive(chunk.runtime)) &&
207+
someInIterable(
208+
chunkGraph.getModuleRuntimes(originModule),
209+
(runtime) =>
210+
intersectRuntime(runtime, chunk.runtime) !== undefined
211+
)
212+
)
213+
) {
214+
return;
215+
}
216+
} else if (
217+
// A chunk whose runtime is elsewhere lifts its entry to the top
218+
// level under the same conditions, and renders it into the module
219+
// registry otherwise.
220+
JavascriptModulesPlugin._getEsmEntryModuleToInline({
221+
chunk,
222+
chunkGraph,
223+
moduleGraph,
224+
runtimeTemplate,
225+
codeGenerationResults
226+
}) !== module
227+
) {
228+
return;
229+
}
187230
const codeGenResult = codeGenerationResults.get(
188231
module,
189232
chunk.runtime
@@ -212,45 +255,32 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin {
212255
}
213256
}
214257

215-
// The helpers land in the runtime, not in this chunk, so what still
216-
// needs them is asked of every chunk sharing the entrypoint — the
217-
// runtime chunk, and whatever `splitChunks` moved out of the entry.
218-
/** @type {Set<Chunk>} */
219-
const siblings = new Set([chunk]);
220-
for (const [
221-
,
222-
entrypoint
223-
] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) {
224-
if (!entrypoint) continue;
225-
for (const sibling of entrypoint.chunks) siblings.add(sibling);
226-
}
227-
258+
// The entrypoint loads as this chunk alone, so what still needs the
259+
// helpers is whatever else it holds beside the entry.
228260
let otherNeedsDefine = false;
229261
let otherNeedsNamespaceObject = false;
230262
let otherNeedsExports = false;
231263
let otherNeedsRequireScope = false;
232-
outer: for (const sibling of siblings) {
233-
for (const m of chunkGraph.getChunkModulesIterable(sibling)) {
234-
if (m === module) continue;
235-
const requirements = chunkGraph.getModuleRuntimeRequirements(
236-
m,
237-
sibling.runtime
238-
);
239-
if (!requirements) continue;
240-
if (requirements.has(RuntimeGlobals.definePropertyGetters)) {
241-
otherNeedsDefine = true;
242-
}
243-
if (requirements.has(RuntimeGlobals.makeNamespaceObject)) {
244-
otherNeedsNamespaceObject = true;
245-
}
246-
if (requirements.has(RuntimeGlobals.exports)) {
247-
otherNeedsExports = true;
248-
}
249-
if (requirements.has(RuntimeGlobals.requireScope)) {
250-
otherNeedsRequireScope = true;
251-
}
252-
if (otherNeedsDefine) break outer;
264+
for (const m of chunkGraph.getChunkModulesIterable(chunk)) {
265+
if (m === module) continue;
266+
const requirements = chunkGraph.getModuleRuntimeRequirements(
267+
m,
268+
chunk.runtime
269+
);
270+
if (!requirements) continue;
271+
if (requirements.has(RuntimeGlobals.definePropertyGetters)) {
272+
otherNeedsDefine = true;
273+
}
274+
if (requirements.has(RuntimeGlobals.makeNamespaceObject)) {
275+
otherNeedsNamespaceObject = true;
276+
}
277+
if (requirements.has(RuntimeGlobals.exports)) {
278+
otherNeedsExports = true;
279+
}
280+
if (requirements.has(RuntimeGlobals.requireScope)) {
281+
otherNeedsRequireScope = true;
253282
}
283+
if (otherNeedsDefine) break;
254284
}
255285

256286
if (otherNeedsDefine) return;
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import "./side";
2+
3+
export const keep = "keep";
4+
export default "main";
5+
6+
it("should define the export helpers the entry factory reads", () => {
7+
expect(keep).toBe("keep");
8+
});
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Stays an ES module exporting nothing: an export the entry reads would have it
2+
// ask for the export helpers itself, and a default the entry interops with would
3+
// put `__webpack_require__.n` in the entry's own source.
4+
export {};
5+
6+
const executed = [];
7+
8+
executed.push("side");
9+
10+
it("should execute the module that loads with the entry", () => {
11+
expect(executed).toEqual(["side"]);
12+
});
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
"use strict";
2+
3+
module.exports = {
4+
findBundle(_i, options) {
5+
return `./${Object.keys(options.entry)[0]}.mjs`;
6+
}
7+
};
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"use strict";
2+
3+
/** @import { Configuration } from "../../../../" */
4+
5+
/**
6+
* The split chunk loads with the entry, so the entry is executed as a factory
7+
* rather than inlined into the startup, and the export definitions it left out
8+
* on demand are put back there — the helpers they read have to stay.
9+
* @param {string} name config name
10+
* @param {boolean} concatenateModules whether to concatenate modules
11+
* @returns {Configuration} configuration
12+
*/
13+
const createConfig = (name, concatenateModules) => ({
14+
mode: "production",
15+
name,
16+
entry: { [name]: "./index.js" },
17+
output: {
18+
module: true,
19+
filename: "[name].mjs",
20+
chunkFormat: "module",
21+
library: {
22+
type: "module"
23+
}
24+
},
25+
optimization: {
26+
minimize: false,
27+
concatenateModules,
28+
splitChunks: {
29+
cacheGroups: {
30+
side: {
31+
test: /side\.js$/,
32+
chunks: "all",
33+
name: "side",
34+
enforce: true
35+
}
36+
}
37+
}
38+
}
39+
});
40+
41+
/** @type {Configuration[]} */
42+
module.exports = [
43+
createConfig("concat", true),
44+
createConfig("no-concat", false)
45+
];

0 commit comments

Comments
 (0)