Skip to content

Commit 5f6f270

Browse files
feat(entry): add entry.mergeExports to expose every entry module's exports
An entry with several modules in `import` exports only the last one's, so a `library` build silently drops the rest and tree shaking removes them in production (#15936). Making that the default would break a contract webpack has kept since 4, so merging is opt-in per entry. `__webpack_require__.me` merges the entry namespaces in order, later modules winning a conflicting name, and `ModuleLibraryPlugin` widens its `export {}` clause to their union. Entry modules that run behind a chunk load cannot be read back, so those configurations error instead of falling back silently.
1 parent 98d61c2 commit 5f6f270

33 files changed

Lines changed: 478 additions & 36 deletions
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+
Add `entry.<name>.mergeExports` to expose the exports of every entry module.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,11 @@ export type UmdAmdContainer = string;
202202
* If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module.
203203
*/
204204
export type UmdNamedDefine = boolean;
205+
/**
206+
* Expose the exports of every module in 'import' instead of only the last one's. Modules are merged in order, so a later one wins a conflicting export name. Only observable through 'output.library'.
207+
* @since 5.111.0
208+
*/
209+
export type EntryMergeExports = boolean;
205210
/**
206211
* The 'publicPath' specifies the public URL address of the output files when referenced in a browser.
207212
*/
@@ -1383,6 +1388,10 @@ export interface EntryDescription {
13831388
* Options for library.
13841389
*/
13851390
library?: LibraryOptions;
1391+
/**
1392+
* Expose the exports of every module in 'import' instead of only the last one's. Modules are merged in order, so a later one wins a conflicting export name. Only observable through 'output.library'.
1393+
*/
1394+
mergeExports?: EntryMergeExports;
13861395
/**
13871396
* The 'publicPath' specifies the public URL address of the output files when referenced in a browser.
13881397
*/
@@ -4533,6 +4542,10 @@ export interface EntryDescriptionNormalized {
45334542
* Options for library.
45344543
*/
45354544
library?: LibraryOptions;
4545+
/**
4546+
* Expose the exports of every module in 'import' instead of only the last one's. Modules are merged in order, so a later one wins a conflicting export name. Only observable through 'output.library'.
4547+
*/
4548+
mergeExports?: EntryMergeExports;
45364549
/**
45374550
* The 'publicPath' specifies the public URL address of the output files when referenced in a browser.
45384551
*/

‎lib/EntryOptionPlugin.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ class EntryOptionPlugin {
118118
asyncChunks: desc.asyncChunks,
119119
wasmLoading: desc.wasmLoading,
120120
worker: desc.worker,
121-
library: desc.library
121+
library: desc.library,
122+
mergeExports: desc.mergeExports
122123
};
123124
if (desc.chunkLoading) {
124125
const EnableChunkLoadingPlugin = require("./javascript/EnableChunkLoadingPlugin");

‎lib/RuntimeGlobals.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,11 @@ module.exports.makeNamespaceObject = "__webpack_require__.r";
334334
*/
335335
module.exports.makeOptimizedDeferredNamespaceObject = "__webpack_require__.zO";
336336

337+
/**
338+
* the function merging the exports objects of several entry modules into one
339+
*/
340+
module.exports.mergeExports = "__webpack_require__.me";
341+
337342
/**
338343
* the internal module object
339344
*/

‎lib/RuntimePlugin.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ const getMakeOptimizedDeferredNamespaceObjectRuntimeModule = lazyModule(
103103
const getMakeNamespaceObjectRuntimeModule = lazyModule(() =>
104104
require("./runtime/MakeNamespaceObjectRuntimeModule")
105105
);
106+
const getMergeExportsRuntimeModule = lazyModule(() =>
107+
require("./runtime/MergeExportsRuntimeModule")
108+
);
106109
const getNonceRuntimeModule = lazyModule(() =>
107110
require("./runtime/NonceRuntimeModule")
108111
);
@@ -149,6 +152,7 @@ const GLOBALS_ON_REQUIRE = [
149152
RuntimeGlobals.getFullHash,
150153
RuntimeGlobals.global,
151154
RuntimeGlobals.makeNamespaceObject,
155+
RuntimeGlobals.mergeExports,
152156
RuntimeGlobals.moduleCache,
153157
RuntimeGlobals.moduleFactories,
154158
RuntimeGlobals.moduleFactoriesAddOnly,
@@ -202,6 +206,7 @@ const TREE_DEPENDENCIES = {
202206
RuntimeGlobals.createFakeNamespaceObject,
203207
RuntimeGlobals.require
204208
],
209+
[RuntimeGlobals.mergeExports]: [RuntimeGlobals.makeNamespaceObject],
205210
[RuntimeGlobals.initializeSharing]: [RuntimeGlobals.shareScopeMap],
206211
[RuntimeGlobals.shareScopeMap]: [RuntimeGlobals.hasOwnProperty],
207212
[RuntimeGlobals.constructRequire]: [RuntimeGlobals.require]
@@ -212,6 +217,7 @@ const TREE_DEPENDENCIES = {
212217
/** @type {[string, () => Promise<new () => RuntimeModule>][]} */
213218
const SIMPLE_TREE_RUNTIME_MODULES = [
214219
[RuntimeGlobals.makeNamespaceObject, getMakeNamespaceObjectRuntimeModule],
220+
[RuntimeGlobals.mergeExports, getMergeExportsRuntimeModule],
215221
[
216222
RuntimeGlobals.createFakeNamespaceObject,
217223
getCreateFakeNamespaceObjectRuntimeModule

‎lib/config/normalization.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -681,7 +681,8 @@ const getNormalizedEntryStatic = (entry) => {
681681
? value.dependOn
682682
: [value.dependOn])
683683
),
684-
library: value.library
684+
library: value.library,
685+
mergeExports: value.mergeExports
685686
};
686687
}
687688
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author Alexander Akait @alexander-akait
4+
*/
5+
6+
"use strict";
7+
8+
const WebpackError = require("./WebpackError");
9+
10+
/** @import Chunk from "../Chunk" */
11+
12+
/**
13+
* Error raised when an entry asks for `mergeExports` but its modules do not all
14+
* run during the chunk's own startup, so their exports cannot be merged.
15+
*/
16+
class UnmergeableEntryExportsError extends WebpackError {
17+
/**
18+
* Captures the chunk whose entry modules run behind a chunk load.
19+
* @param {Chunk} chunk the chunk carrying the entry
20+
*/
21+
constructor(chunk) {
22+
super(
23+
`Entry "${chunk.name || chunk.id}" can't merge the exports of its modules because they don't all run when this chunk starts up. Remove 'mergeExports', or remove the 'dependOn'/runtime splitting that defers them.`
24+
);
25+
26+
/** @type {string} */
27+
this.name = "UnmergeableEntryExportsError";
28+
/** @type {Chunk} */
29+
this.chunk = chunk;
30+
}
31+
}
32+
33+
module.exports = UnmergeableEntryExportsError;

‎lib/javascript/JavascriptModulesPlugin.js‎

Lines changed: 88 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ const NormalModule = require("../NormalModule");
3535
const RuntimeGlobals = require("../RuntimeGlobals");
3636
const Template = require("../Template");
3737
const { tryRunOrWebpackError } = require("../errors/HookWebpackError");
38+
const UnmergeableEntryExportsError = require("../errors/UnmergeableEntryExportsError");
3839
const { last, someInIterable } = require("../util/IterableHelpers");
3940
const StringXor = require("../util/StringXor");
4041
const { compareModulesByFullName } = require("../util/comparators");
@@ -57,7 +58,11 @@ const JavascriptGenerator = require("./JavascriptGenerator");
5758
const JavascriptModule = require("./JavascriptModule");
5859
const JavascriptParser = require("./JavascriptParser");
5960
const analyzeScope = require("./ScopeAnalyzer");
60-
const { renderAwaitedEntries } = require("./StartupHelpers");
61+
const {
62+
entryStartupAwaitsChunks,
63+
mergedEntryModules,
64+
renderAwaitedEntries
65+
} = require("./StartupHelpers");
6166
const { releaseParserCaches } = require("./syntax");
6267

6368
/**
@@ -703,16 +708,39 @@ class JavascriptModulesPlugin {
703708
compilation.hooks.additionalTreeRuntimeRequirements.tap(
704709
PLUGIN_NAME,
705710
(chunk, set, { chunkGraph }) => {
706-
if (
707-
!set.has(RuntimeGlobals.startupNoDefault) &&
708-
chunkGraph.hasChunkEntryDependentChunks(chunk)
709-
) {
711+
if (set.has(RuntimeGlobals.startupNoDefault)) return;
712+
const dependentChunks =
713+
chunkGraph.hasChunkEntryDependentChunks(chunk);
714+
if (dependentChunks) {
710715
set.add(RuntimeGlobals.onChunksLoaded);
711716
set.add(RuntimeGlobals.exports);
712717
set.add(RuntimeGlobals.require);
713718
}
719+
if (
720+
dependentChunks ||
721+
mergedEntryModules(chunk, chunkGraph) === undefined
722+
) {
723+
return;
724+
}
725+
set.add(RuntimeGlobals.mergeExports);
726+
set.add(RuntimeGlobals.exports);
714727
}
715728
);
729+
compilation.hooks.afterChunks.tap(PLUGIN_NAME, (chunks) => {
730+
const { chunkGraph } = compilation;
731+
for (const chunk of chunks) {
732+
// Merging reads each entry back right after it ran, which
733+
// only the bootstrap of the runtime-carrying chunk can do.
734+
if (
735+
mergedEntryModules(chunk, chunkGraph) !== undefined &&
736+
(!chunk.hasRuntime() ||
737+
chunkGraph.hasChunkEntryDependentChunks(chunk) ||
738+
entryStartupAwaitsChunks(chunkGraph, chunk))
739+
) {
740+
compilation.errors.push(new UnmergeableEntryExportsError(chunk));
741+
}
742+
}
743+
});
716744
compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => {
717745
const source =
718746
options.codeGenerationResult.sources.get(JAVASCRIPT_TYPE);
@@ -1688,8 +1716,20 @@ class JavascriptModulesPlugin {
16881716
runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&
16891717
runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)
16901718
);
1719+
const merge = mergedEntryModules(chunk, chunkGraph) !== undefined;
1720+
if (merge && result.allowInlineStartup) {
1721+
buf2.push(
1722+
"// The exports of the entry modules are merged so they can't be inlined"
1723+
);
1724+
result.allowInlineStartup = false;
1725+
}
16911726
/** @type {string[]} */
16921727
const awaitedEntries = [];
1728+
/** @type {string[]} */
1729+
const mergedEntries = [];
1730+
// An async entry webpack does not await here hands back a promise,
1731+
// which only resolves to the exports the merge needs.
1732+
let mergeAwaitsEntries = false;
16931733
let i = jsEntries.length;
16941734
for (const [entryModule, entrypoint] of jsEntries) {
16951735
const chunks =
@@ -1805,24 +1845,32 @@ class JavascriptModulesPlugin {
18051845
// with `let` (or `var` if `let` is unsupported) so
18061846
// reassignment is allowed.
18071847
const exportsDecl = runtimeTemplate.renderLet();
1848+
// Merging reads every entry back, so each one needs a variable of
1849+
// its own; without it only the last entry (`i === 0`) is exported.
1850+
const target =
1851+
i === 0 && !merge
1852+
? RuntimeGlobals.exports
1853+
: `${RuntimeGlobals.exports}_${i}`;
1854+
if (merge) mergedEntries.push(target);
18081855
if (chunks.length > 0) {
18091856
const awaitEntry =
18101857
canAwaitEntry && moduleGraph.isAsync(entryModule);
1811-
const target =
1812-
i === 0
1813-
? RuntimeGlobals.exports
1814-
: `${RuntimeGlobals.exports}_${i}`;
18151858
// The wrapper hands back nothing until the flush below runs the
1816-
// entry, so an awaited one is caught by the entry call itself.
1817-
if (awaitEntry && i !== 0) buf2.push(`${exportsDecl} ${target};`);
1859+
// entry, so a captured one is caught by the entry call itself.
1860+
const capture = awaitEntry || merge;
1861+
if (capture && target !== RuntimeGlobals.exports) {
1862+
buf2.push(`${exportsDecl} ${target};`);
1863+
}
18181864
const entryCall = `${RuntimeGlobals.require}(${moduleIdExpr})`;
18191865
buf2.push(
1820-
`${i === 0 ? `${exportsDecl} ${RuntimeGlobals.exports} = ` : ""}${
1821-
RuntimeGlobals.onChunksLoaded
1822-
}(undefined, ${JSON.stringify(
1866+
`${
1867+
i === 0 && !merge
1868+
? `${exportsDecl} ${RuntimeGlobals.exports} = `
1869+
: ""
1870+
}${RuntimeGlobals.onChunksLoaded}(undefined, ${JSON.stringify(
18231871
chunks.map((c) => c.id)
18241872
)}, ${runtimeTemplate.returningFunction(
1825-
awaitEntry ? `(${target} = ${entryCall})` : entryCall
1873+
capture ? `(${target} = ${entryCall})` : entryCall
18261874
)})`
18271875
);
18281876
if (awaitEntry) awaitedEntries.push(target);
@@ -1831,18 +1879,18 @@ class JavascriptModulesPlugin {
18311879
// which orphans its rejection.
18321880
const awaitEntry =
18331881
canAwaitEntry && moduleGraph.isAsync(entryModule);
1834-
const target =
1835-
i === 0
1836-
? RuntimeGlobals.exports
1837-
: `${RuntimeGlobals.exports}_${i}`;
1838-
const needsDecl = i === 0 || awaitEntry;
1882+
const needsDecl = i === 0 || awaitEntry || merge;
18391883
buf2.push(
18401884
`${needsDecl ? `${exportsDecl} ${target} = ` : ""}${RuntimeGlobals.require}(${moduleIdExpr});`
18411885
);
1842-
if (awaitEntry) awaitedEntries.push(target);
1886+
if (awaitEntry) {
1887+
awaitedEntries.push(target);
1888+
} else if (merge && moduleGraph.isAsync(entryModule)) {
1889+
mergeAwaitsEntries = true;
1890+
}
18431891
} else {
1844-
if (i === 0) {
1845-
buf2.push(`${exportsDecl} ${RuntimeGlobals.exports} = {};`);
1892+
if (i === 0 || merge) {
1893+
buf2.push(`${exportsDecl} ${target} = {};`);
18461894
}
18471895
const needThisAsExports = entryRuntimeRequirements.has(
18481896
RuntimeGlobals.thisAsExports
@@ -1854,7 +1902,7 @@ class JavascriptModulesPlugin {
18541902
requireScopeUsed ||
18551903
entryRuntimeRequirements.has(RuntimeGlobals.exports)
18561904
) {
1857-
const exportsArg = i === 0 ? RuntimeGlobals.exports : "{}";
1905+
const exportsArg = i === 0 || merge ? target : "{}";
18581906
args.push("0", exportsArg);
18591907
if (requireScopeUsed) {
18601908
args.push(RuntimeGlobals.require);
@@ -1866,7 +1914,7 @@ class JavascriptModulesPlugin {
18661914
if (needThisAsExports) {
18671915
const comma = args.length ? "," : "";
18681916
return `__webpack_modules__[${moduleIdExpr}].call(${
1869-
RuntimeGlobals.exports
1917+
merge ? target : RuntimeGlobals.exports
18701918
}${comma}${args.join(",")});`;
18711919
}
18721920
return `__webpack_modules__[${moduleIdExpr}](${args.join(
@@ -1879,10 +1927,24 @@ class JavascriptModulesPlugin {
18791927
}
18801928
if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) {
18811929
buf2.push(
1882-
`${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
1930+
merge
1931+
? `${RuntimeGlobals.onChunksLoaded}();`
1932+
: `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
18831933
);
18841934
}
18851935
buf2.push(...renderAwaitedEntries(awaitedEntries));
1936+
// Every entry has run by now, so the merge sees the final exports of
1937+
// each one — behind one promise where an entry is still settling.
1938+
if (merge) {
1939+
const list = `[${mergedEntries.join(", ")}]`;
1940+
buf2.push(
1941+
`${runtimeTemplate.renderLet()} ${RuntimeGlobals.exports} = ${
1942+
mergeAwaitsEntries
1943+
? `Promise.all(${list}).then(${RuntimeGlobals.mergeExports})`
1944+
: `${RuntimeGlobals.mergeExports}(${list})`
1945+
};`
1946+
);
1947+
}
18861948
if (
18871949
runtimeRequirements.has(RuntimeGlobals.startup) ||
18881950
(runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&

0 commit comments

Comments
 (0)