Skip to content

Commit f393d01

Browse files
feat(library): add library.mergeEntryExports to expose every entry module
An entry with several modules 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 — and it belongs to `library`, since an application's entry exports nothing anyone reads. It works on `output.library` and on `entry.<name>.library` alike. The merged object is written out at compile time as a `__webpack_require__.d` call over the entry modules' known exports, so every name stays visible to an analyzer and no runtime helper is needed. Conflicts follow ES modules: a name more than one module binds differently is left out with a warning, while one they all take from the same binding survives. An entry providing unknown exports, or an async one this output can't await, is an error rather than a thinner library.
1 parent 358df69 commit f393d01

64 files changed

Lines changed: 858 additions & 55 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
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 `library.mergeEntryExports` to expose the exports of every entry module.

‎lib/config/normalization.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,7 @@ const getNormalizedWebpackOptions = (config) => ({
493493
output.libraryExport !== undefined
494494
? output.libraryExport
495495
: libraryBase.export,
496+
mergeEntryExports: libraryBase.mergeEntryExports,
496497
name: libraryBase.name,
497498
umdAmdContainer: libraryBase.umdAmdContainer,
498499
umdNamedDefine:

‎lib/dependencies/HarmonyExportInitFragment.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,8 +287,8 @@ class HarmonyExportInitFragment extends InitFragment {
287287
// emit it, and by then the requirement set is closed.
288288
runtimeRequirements.add(RuntimeGlobals.exports);
289289
runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
290-
// Only this fragment emits the array form, so the runtime helper drops the
291-
// branch reading it unless this asks for it.
290+
// The runtime helper drops the branch reading the array form unless an
291+
// emitter of it asks, so every emitter has to.
292292
runtimeRequirements.add(RuntimeGlobals.definePropertyGettersFromArray);
293293
definePart = `/* harmony export */ ${
294294
RuntimeGlobals.definePropertyGetters
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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 "../graph/Chunk" */
11+
12+
/**
13+
* Warning raised when several modules of a `mergeEntryExports` entry bind the same
14+
* export name, which leaves the name out of the merged exports.
15+
*/
16+
class ConflictingEntryExportsWarning extends WebpackError {
17+
/**
18+
* Captures the entry's chunk and the names it cannot expose.
19+
* @param {Chunk} chunk the chunk carrying the entry
20+
* @param {string[]} names the conflicting export names
21+
*/
22+
constructor(chunk, names) {
23+
super(
24+
`Entry "${chunk.name || chunk.id}" contains conflicting exports for the ${
25+
names.length === 1 ? "name" : "names"
26+
} ${names.map((name) => `'${name}'`).join(", ")}, so ${
27+
names.length === 1 ? "it is" : "they are"
28+
} not exposed by the merged exports.`
29+
);
30+
31+
/** @type {string} */
32+
this.name = "ConflictingEntryExportsWarning";
33+
/** @type {Chunk} */
34+
this.chunk = chunk;
35+
}
36+
}
37+
38+
module.exports = ConflictingEntryExportsWarning;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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 "../graph/Chunk" */
11+
12+
/**
13+
* Error raised when an entry asks for `mergeEntryExports` but webpack cannot build
14+
* the merged exports object from its modules.
15+
*/
16+
class UnmergeableEntryExportsError extends WebpackError {
17+
/**
18+
* Captures the chunk carrying the entry and why its exports cannot be merged.
19+
* @param {Chunk} chunk the chunk carrying the entry
20+
* @param {string} reason what stands in the way, as a sentence fragment
21+
*/
22+
constructor(chunk, reason) {
23+
super(
24+
`Entry "${chunk.name || chunk.id}" can't merge the exports of its modules because ${reason}. Remove 'library.mergeEntryExports', or re-export the modules from a single entry module instead.`
25+
);
26+
27+
/** @type {string} */
28+
this.name = "UnmergeableEntryExportsError";
29+
/** @type {Chunk} */
30+
this.chunk = chunk;
31+
}
32+
}
33+
34+
module.exports = UnmergeableEntryExportsError;

‎lib/javascript/JavascriptModulesPlugin.js‎

Lines changed: 169 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ const {
2222
* WebpackRequire
2323
* } from "../Compilation"
2424
*/
25+
const ConflictingEntryExportsWarning = require("../errors/ConflictingEntryExportsWarning");
2526
const { tryRunOrWebpackError } = require("../errors/HookWebpackError");
27+
const UnmergeableEntryExportsError = require("../errors/UnmergeableEntryExportsError");
2628
const HotUpdateChunk = require("../graph/HotUpdateChunk");
2729
const { JAVASCRIPT_TYPE } = require("../module/ModuleSourceTypeConstants");
2830
const {
@@ -50,14 +52,22 @@ const {
5052
const createHash = require("../util/createHash");
5153
const createHooksRegistry = require("../util/createHooksRegistry");
5254
const { digestNonNumericOnlyWithFull } = require("../util/nonNumericOnlyHash");
55+
const { propertyAccess } = require("../util/property");
5356
const { removeBOMFromResult } = require("../util/removeBOM");
5457
const { intersectRuntime } = require("../util/runtime");
5558
const { getAllChunks } = require("./ChunkHelpers");
5659
const JavascriptGenerator = require("./JavascriptGenerator");
5760
const JavascriptModule = require("./JavascriptModule");
5861
const JavascriptParser = require("./JavascriptParser");
62+
const {
63+
getMergedExports,
64+
mergedEntryModules
65+
} = require("./MergedEntryExports");
5966
const analyzeScope = require("./ScopeAnalyzer");
60-
const { renderAwaitedEntries } = require("./StartupHelpers");
67+
const {
68+
entryStartupAwaitsChunks,
69+
renderAwaitedEntries
70+
} = require("./StartupHelpers");
6171
const { releaseParserCaches } = require("./syntax-parser");
6272

6373
/**
@@ -703,16 +713,97 @@ class JavascriptModulesPlugin {
703713
compilation.hooks.additionalTreeRuntimeRequirements.tap(
704714
PLUGIN_NAME,
705715
(chunk, set, { chunkGraph }) => {
706-
if (
707-
!set.has(RuntimeGlobals.startupNoDefault) &&
708-
chunkGraph.hasChunkEntryDependentChunks(chunk)
709-
) {
716+
if (set.has(RuntimeGlobals.startupNoDefault)) return;
717+
if (chunkGraph.hasChunkEntryDependentChunks(chunk)) {
710718
set.add(RuntimeGlobals.onChunksLoaded);
711719
set.add(RuntimeGlobals.exports);
712720
set.add(RuntimeGlobals.require);
721+
return;
722+
}
723+
const merged = mergedEntryModules(
724+
chunk,
725+
chunkGraph,
726+
compilation.outputOptions
727+
);
728+
if (merged === undefined) return;
729+
const { exports, namespace } = getMergedExports(
730+
merged,
731+
compilation.moduleGraph,
732+
chunk.runtime
733+
);
734+
set.add(RuntimeGlobals.exports);
735+
if (namespace) set.add(RuntimeGlobals.makeNamespaceObject);
736+
if (exports.length > 0) {
737+
set.add(RuntimeGlobals.definePropertyGetters);
738+
set.add(RuntimeGlobals.definePropertyGettersFromArray);
713739
}
714740
}
715741
);
742+
compilation.hooks.afterChunks.tap(PLUGIN_NAME, (chunks) => {
743+
const { chunkGraph, moduleGraph, outputOptions, runtimeTemplate } =
744+
compilation;
745+
for (const chunk of chunks) {
746+
const merged = mergedEntryModules(chunk, chunkGraph, outputOptions);
747+
if (merged === undefined) continue;
748+
// Merging reads each entry back right after it ran, which
749+
// only the bootstrap of the runtime-carrying chunk can do.
750+
if (
751+
!chunk.hasRuntime() ||
752+
chunkGraph.hasChunkEntryDependentChunks(chunk) ||
753+
entryStartupAwaitsChunks(chunkGraph, chunk)
754+
) {
755+
compilation.errors.push(
756+
new UnmergeableEntryExportsError(
757+
chunk,
758+
"they don't all run when this chunk starts up"
759+
)
760+
);
761+
continue;
762+
}
763+
// An async entry hands back a promise the merged object would
764+
// read names off, so it has to be awaited before the merge.
765+
if (
766+
!(
767+
runtimeTemplate.isModule() &&
768+
runtimeTemplate.supportsTopLevelAwait()
769+
) &&
770+
merged.some((module) => moduleGraph.isAsync(module))
771+
) {
772+
compilation.errors.push(
773+
new UnmergeableEntryExportsError(
774+
chunk,
775+
"one of them is async and this output can't await it at the top level (see 'output.environment.topLevelAwait')"
776+
)
777+
);
778+
continue;
779+
}
780+
const { conflicting, unknownExports } = getMergedExports(
781+
merged,
782+
moduleGraph,
783+
chunk.runtime
784+
);
785+
if (unknownExports.length > 0) {
786+
compilation.errors.push(
787+
new UnmergeableEntryExportsError(
788+
chunk,
789+
`webpack can't tell what ${unknownExports
790+
.map((module) =>
791+
module.readableIdentifier(
792+
runtimeTemplate.requestShortener
793+
)
794+
)
795+
.join(", ")} exports`
796+
)
797+
);
798+
continue;
799+
}
800+
if (conflicting.length > 0) {
801+
compilation.warnings.push(
802+
new ConflictingEntryExportsWarning(chunk, conflicting)
803+
);
804+
}
805+
}
806+
});
716807
compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => {
717808
const source =
718809
options.codeGenerationResult.sources.get(JAVASCRIPT_TYPE);
@@ -1680,9 +1771,16 @@ class JavascriptModulesPlugin {
16801771
entryOptions && entryOptions.library !== undefined
16811772
? entryOptions.library
16821773
: runtimeTemplate.outputOptions.library;
1683-
// A module library awaits the entry itself, in `ModuleLibraryPlugin`.
1774+
const mergedModules = mergedEntryModules(
1775+
chunk,
1776+
chunkGraph,
1777+
runtimeTemplate.outputOptions
1778+
);
1779+
const merge = mergedModules !== undefined;
1780+
// A module library awaits the entry itself, in `ModuleLibraryPlugin`
1781+
// — but it only sees the merged object, so merging awaits them here.
16841782
const awaitedByLibrary =
1685-
library !== undefined && library.type === "module";
1783+
!merge && library !== undefined && library.type === "module";
16861784
// `await` is legal only at an ESM chunk's top level, never in the
16871785
// startup function below, and only where the target parses it.
16881786
const canAwaitEntry =
@@ -1694,8 +1792,16 @@ class JavascriptModulesPlugin {
16941792
runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&
16951793
runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)
16961794
);
1795+
if (merge && result.allowInlineStartup) {
1796+
buf2.push(
1797+
"// The exports of the entry modules are merged so they can't be inlined"
1798+
);
1799+
result.allowInlineStartup = false;
1800+
}
16971801
/** @type {string[]} */
16981802
const awaitedEntries = [];
1803+
/** @type {Map<Module, string>} */
1804+
const mergedTargets = new Map();
16991805
let i = jsEntries.length;
17001806
for (const [entryModule, entrypoint] of jsEntries) {
17011807
const chunks =
@@ -1813,24 +1919,32 @@ class JavascriptModulesPlugin {
18131919
// `onChunksLoaded` wrapper, a top-level `await` bridge or other
18141920
// codegen, so it is never declared as a constant.
18151921
const exportsDecl = runtimeTemplate.renderLet();
1922+
// Merging reads every entry back, so each one needs a variable of
1923+
// its own; without it only the last entry (`i === 0`) is exported.
1924+
const target =
1925+
i === 0 && !merge
1926+
? RuntimeGlobals.exports
1927+
: `${RuntimeGlobals.exports}_${i}`;
1928+
if (merge) mergedTargets.set(entryModule, target);
18161929
if (chunks.length > 0) {
18171930
const awaitEntry =
18181931
canAwaitEntry && moduleGraph.isAsync(entryModule);
1819-
const target =
1820-
i === 0
1821-
? RuntimeGlobals.exports
1822-
: `${RuntimeGlobals.exports}_${i}`;
18231932
// The wrapper hands back nothing until the flush below runs the
1824-
// entry, so an awaited one is caught by the entry call itself.
1825-
if (awaitEntry && i !== 0) buf2.push(`${exportsDecl} ${target};`);
1933+
// entry, so a captured one is caught by the entry call itself.
1934+
const capture = awaitEntry || merge;
1935+
if (capture && target !== RuntimeGlobals.exports) {
1936+
buf2.push(`${exportsDecl} ${target};`);
1937+
}
18261938
const entryCall = `${RuntimeGlobals.require}(${moduleIdExpr})`;
18271939
buf2.push(
1828-
`${i === 0 ? `${exportsDecl} ${RuntimeGlobals.exports} = ` : ""}${
1829-
RuntimeGlobals.onChunksLoaded
1830-
}(undefined, ${JSON.stringify(
1940+
`${
1941+
i === 0 && !merge
1942+
? `${exportsDecl} ${RuntimeGlobals.exports} = `
1943+
: ""
1944+
}${RuntimeGlobals.onChunksLoaded}(undefined, ${JSON.stringify(
18311945
chunks.map((c) => c.id)
18321946
)}, ${runtimeTemplate.returningFunction(
1833-
awaitEntry ? `(${target} = ${entryCall})` : entryCall
1947+
capture ? `(${target} = ${entryCall})` : entryCall
18341948
)})`
18351949
);
18361950
if (awaitEntry) awaitedEntries.push(target);
@@ -1839,18 +1953,14 @@ class JavascriptModulesPlugin {
18391953
// which orphans its rejection.
18401954
const awaitEntry =
18411955
canAwaitEntry && moduleGraph.isAsync(entryModule);
1842-
const target =
1843-
i === 0
1844-
? RuntimeGlobals.exports
1845-
: `${RuntimeGlobals.exports}_${i}`;
1846-
const needsDecl = i === 0 || awaitEntry;
1956+
const needsDecl = i === 0 || awaitEntry || merge;
18471957
buf2.push(
18481958
`${needsDecl ? `${exportsDecl} ${target} = ` : ""}${RuntimeGlobals.require}(${moduleIdExpr});`
18491959
);
18501960
if (awaitEntry) awaitedEntries.push(target);
18511961
} else {
1852-
if (i === 0) {
1853-
buf2.push(`${exportsDecl} ${RuntimeGlobals.exports} = {};`);
1962+
if (i === 0 || merge) {
1963+
buf2.push(`${exportsDecl} ${target} = {};`);
18541964
}
18551965
const needThisAsExports = entryRuntimeRequirements.has(
18561966
RuntimeGlobals.thisAsExports
@@ -1862,7 +1972,7 @@ class JavascriptModulesPlugin {
18621972
requireScopeUsed ||
18631973
entryRuntimeRequirements.has(RuntimeGlobals.exports)
18641974
) {
1865-
const exportsArg = i === 0 ? RuntimeGlobals.exports : "{}";
1975+
const exportsArg = i === 0 || merge ? target : "{}";
18661976
args.push("0", exportsArg);
18671977
if (requireScopeUsed) {
18681978
args.push(RuntimeGlobals.require);
@@ -1874,7 +1984,7 @@ class JavascriptModulesPlugin {
18741984
if (needThisAsExports) {
18751985
const comma = args.length ? "," : "";
18761986
return `__webpack_modules__[${moduleIdExpr}].call(${
1877-
RuntimeGlobals.exports
1987+
merge ? target : RuntimeGlobals.exports
18781988
}${comma}${args.join(",")});`;
18791989
}
18801990
return `__webpack_modules__[${moduleIdExpr}](${args.join(
@@ -1887,10 +1997,42 @@ class JavascriptModulesPlugin {
18871997
}
18881998
if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) {
18891999
buf2.push(
1890-
`${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
2000+
merge
2001+
? `${RuntimeGlobals.onChunksLoaded}();`
2002+
: `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
18912003
);
18922004
}
18932005
buf2.push(...renderAwaitedEntries(awaitedEntries));
2006+
// Every entry has run by now, and the getters below read through to
2007+
// whichever one provides each name.
2008+
if (merge) {
2009+
const { exports, namespace } = getMergedExports(
2010+
/** @type {Module[]} */ (mergedModules),
2011+
moduleGraph,
2012+
chunk.runtime
2013+
);
2014+
buf2.push(
2015+
`${runtimeTemplate.renderLet()} ${RuntimeGlobals.exports} = {};`
2016+
);
2017+
if (namespace) {
2018+
buf2.push(
2019+
`${RuntimeGlobals.makeNamespaceObject}(${RuntimeGlobals.exports});`
2020+
);
2021+
}
2022+
if (exports.length > 0) {
2023+
const bindings = exports.map(
2024+
({ name, module, usedName }) =>
2025+
`${JSON.stringify(name)}, ${runtimeTemplate.returningFunction(
2026+
`${mergedTargets.get(module)}${propertyAccess([usedName])}`
2027+
)}`
2028+
);
2029+
buf2.push(
2030+
`${RuntimeGlobals.definePropertyGetters}(${
2031+
RuntimeGlobals.exports
2032+
}, [${bindings.join(", ")}]);`
2033+
);
2034+
}
2035+
}
18942036
if (
18952037
runtimeRequirements.has(RuntimeGlobals.startup) ||
18962038
(runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&

0 commit comments

Comments
 (0)