Skip to content

Commit 459a017

Browse files
feat(library): add library.entryExports to expose every entry module (#22235)
* feat(library): add library.entryExports 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 `entryExports` names it `last` and takes `all` to opt in — on `output.library` and on `entry.<name>.library` alike, since an application's entry exports nothing anyone reads. 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. * fix(library): keep one default export when merging a CommonJS entry A CommonJS entry module adds `export default __webpack_exports__` to a `module` library so it stays importable, and that decision read the last entry module alone. With `entryExports: "all"` an earlier ES module can still export a real `default`, so the bundle carried both and no engine would load it. The synthetic one is now emitted only when every merged module is CommonJS — the same condition that already decided whether to drop `default` from the export clause, and unchanged for a single entry. * test(library): read the commonjs-static exports without matchAll `String.prototype.matchAll` is newer than the Node baseline the harness executes a case under, so the assertion threw on the Node 10 job while passing everywhere else. An `exec` loop reads the same names.
1 parent 432e87e commit 459a017

80 files changed

Lines changed: 1256 additions & 74 deletions

File tree

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.entryExports: "all"` 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+
entryExports: libraryBase.entryExports,
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 an `entryExports: "all"` 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 `entryExports: "all"` 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}. Set 'library.entryExports' back to 'last', 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: 167 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,24 @@ 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+
compilationMergesEntryExports,
64+
getMergedExports,
65+
mergedEntryModules,
66+
mergedEntryModulesOfLibrary
67+
} = require("./MergedEntryExports");
5968
const analyzeScope = require("./ScopeAnalyzer");
60-
const { renderAwaitedEntries } = require("./StartupHelpers");
69+
const {
70+
entryStartupAwaitsChunks,
71+
renderAwaitedEntries
72+
} = require("./StartupHelpers");
6173
const { releaseParserCaches } = require("./syntax-parser");
6274

6375
/**
@@ -703,16 +715,93 @@ class JavascriptModulesPlugin {
703715
compilation.hooks.additionalTreeRuntimeRequirements.tap(
704716
PLUGIN_NAME,
705717
(chunk, set, { chunkGraph }) => {
706-
if (
707-
!set.has(RuntimeGlobals.startupNoDefault) &&
708-
chunkGraph.hasChunkEntryDependentChunks(chunk)
709-
) {
718+
if (set.has(RuntimeGlobals.startupNoDefault)) return;
719+
if (chunkGraph.hasChunkEntryDependentChunks(chunk)) {
710720
set.add(RuntimeGlobals.onChunksLoaded);
711721
set.add(RuntimeGlobals.exports);
712722
set.add(RuntimeGlobals.require);
723+
return;
724+
}
725+
const merged = mergedEntryModules(chunk, chunkGraph, compilation);
726+
if (merged === undefined) return;
727+
const { exports, namespace } = getMergedExports(
728+
merged,
729+
compilation.moduleGraph,
730+
chunk.runtime
731+
);
732+
set.add(RuntimeGlobals.exports);
733+
if (namespace) set.add(RuntimeGlobals.makeNamespaceObject);
734+
if (exports.length > 0) {
735+
set.add(RuntimeGlobals.definePropertyGetters);
736+
set.add(RuntimeGlobals.definePropertyGettersFromArray);
713737
}
714738
}
715739
);
740+
compilation.hooks.afterChunks.tap(PLUGIN_NAME, (chunks) => {
741+
if (!compilationMergesEntryExports(compilation)) return;
742+
const { chunkGraph, moduleGraph, runtimeTemplate } = compilation;
743+
for (const chunk of chunks) {
744+
const merged = mergedEntryModules(chunk, chunkGraph, compilation);
745+
if (merged === undefined) continue;
746+
// Merging reads each entry back right after it ran, which
747+
// only the bootstrap of the runtime-carrying chunk can do.
748+
if (
749+
!chunk.hasRuntime() ||
750+
chunkGraph.hasChunkEntryDependentChunks(chunk) ||
751+
entryStartupAwaitsChunks(chunkGraph, chunk)
752+
) {
753+
compilation.errors.push(
754+
new UnmergeableEntryExportsError(
755+
chunk,
756+
"they don't all run when this chunk starts up"
757+
)
758+
);
759+
continue;
760+
}
761+
// An async entry hands back a promise the merged object would
762+
// read names off, so it has to be awaited before the merge.
763+
if (
764+
!(
765+
runtimeTemplate.isModule() &&
766+
runtimeTemplate.supportsTopLevelAwait()
767+
) &&
768+
merged.some((module) => moduleGraph.isAsync(module))
769+
) {
770+
compilation.errors.push(
771+
new UnmergeableEntryExportsError(
772+
chunk,
773+
"one of them is async and this output can't await it at the top level (see 'output.environment.topLevelAwait')"
774+
)
775+
);
776+
continue;
777+
}
778+
const { conflicting, unknownExports } = getMergedExports(
779+
merged,
780+
moduleGraph,
781+
chunk.runtime
782+
);
783+
if (unknownExports.length > 0) {
784+
compilation.errors.push(
785+
new UnmergeableEntryExportsError(
786+
chunk,
787+
`webpack can't tell what ${unknownExports
788+
.map((module) =>
789+
module.readableIdentifier(
790+
runtimeTemplate.requestShortener
791+
)
792+
)
793+
.join(", ")} exports`
794+
)
795+
);
796+
continue;
797+
}
798+
if (conflicting.length > 0) {
799+
compilation.warnings.push(
800+
new ConflictingEntryExportsWarning(chunk, conflicting)
801+
);
802+
}
803+
}
804+
});
716805
compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => {
717806
const source =
718807
options.codeGenerationResult.sources.get(JAVASCRIPT_TYPE);
@@ -1680,9 +1769,16 @@ class JavascriptModulesPlugin {
16801769
entryOptions && entryOptions.library !== undefined
16811770
? entryOptions.library
16821771
: runtimeTemplate.outputOptions.library;
1683-
// A module library awaits the entry itself, in `ModuleLibraryPlugin`.
1772+
const mergedModules = mergedEntryModulesOfLibrary(
1773+
library,
1774+
chunk,
1775+
chunkGraph
1776+
);
1777+
const merge = mergedModules !== undefined;
1778+
// A module library awaits the entry itself, in `ModuleLibraryPlugin`
1779+
// — but it only sees the merged object, so merging awaits them here.
16841780
const awaitedByLibrary =
1685-
library !== undefined && library.type === "module";
1781+
!merge && library !== undefined && library.type === "module";
16861782
// `await` is legal only at an ESM chunk's top level, never in the
16871783
// startup function below, and only where the target parses it.
16881784
const canAwaitEntry =
@@ -1694,8 +1790,16 @@ class JavascriptModulesPlugin {
16941790
runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&
16951791
runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)
16961792
);
1793+
if (merge && result.allowInlineStartup) {
1794+
buf2.push(
1795+
"// The exports of the entry modules are merged so they can't be inlined"
1796+
);
1797+
result.allowInlineStartup = false;
1798+
}
16971799
/** @type {string[]} */
16981800
const awaitedEntries = [];
1801+
/** @type {Map<Module, string>} */
1802+
const mergedTargets = new Map();
16991803
let i = jsEntries.length;
17001804
for (const [entryModule, entrypoint] of jsEntries) {
17011805
const chunks =
@@ -1813,24 +1917,32 @@ class JavascriptModulesPlugin {
18131917
// `onChunksLoaded` wrapper, a top-level `await` bridge or other
18141918
// codegen, so it is never declared as a constant.
18151919
const exportsDecl = runtimeTemplate.renderLet();
1920+
// Merging reads every entry back, so each one needs a variable of
1921+
// its own; without it only the last entry (`i === 0`) is exported.
1922+
const target =
1923+
i === 0 && !merge
1924+
? RuntimeGlobals.exports
1925+
: `${RuntimeGlobals.exports}_${i}`;
1926+
if (merge) mergedTargets.set(entryModule, target);
18161927
if (chunks.length > 0) {
18171928
const awaitEntry =
18181929
canAwaitEntry && moduleGraph.isAsync(entryModule);
1819-
const target =
1820-
i === 0
1821-
? RuntimeGlobals.exports
1822-
: `${RuntimeGlobals.exports}_${i}`;
18231930
// 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};`);
1931+
// entry, so a captured one is caught by the entry call itself.
1932+
const capture = awaitEntry || merge;
1933+
if (capture && target !== RuntimeGlobals.exports) {
1934+
buf2.push(`${exportsDecl} ${target};`);
1935+
}
18261936
const entryCall = `${RuntimeGlobals.require}(${moduleIdExpr})`;
18271937
buf2.push(
1828-
`${i === 0 ? `${exportsDecl} ${RuntimeGlobals.exports} = ` : ""}${
1829-
RuntimeGlobals.onChunksLoaded
1830-
}(undefined, ${JSON.stringify(
1938+
`${
1939+
i === 0 && !merge
1940+
? `${exportsDecl} ${RuntimeGlobals.exports} = `
1941+
: ""
1942+
}${RuntimeGlobals.onChunksLoaded}(undefined, ${JSON.stringify(
18311943
chunks.map((c) => c.id)
18321944
)}, ${runtimeTemplate.returningFunction(
1833-
awaitEntry ? `(${target} = ${entryCall})` : entryCall
1945+
capture ? `(${target} = ${entryCall})` : entryCall
18341946
)})`
18351947
);
18361948
if (awaitEntry) awaitedEntries.push(target);
@@ -1839,18 +1951,14 @@ class JavascriptModulesPlugin {
18391951
// which orphans its rejection.
18401952
const awaitEntry =
18411953
canAwaitEntry && moduleGraph.isAsync(entryModule);
1842-
const target =
1843-
i === 0
1844-
? RuntimeGlobals.exports
1845-
: `${RuntimeGlobals.exports}_${i}`;
1846-
const needsDecl = i === 0 || awaitEntry;
1954+
const needsDecl = i === 0 || awaitEntry || merge;
18471955
buf2.push(
18481956
`${needsDecl ? `${exportsDecl} ${target} = ` : ""}${RuntimeGlobals.require}(${moduleIdExpr});`
18491957
);
18501958
if (awaitEntry) awaitedEntries.push(target);
18511959
} else {
1852-
if (i === 0) {
1853-
buf2.push(`${exportsDecl} ${RuntimeGlobals.exports} = {};`);
1960+
if (i === 0 || merge) {
1961+
buf2.push(`${exportsDecl} ${target} = {};`);
18541962
}
18551963
const needThisAsExports = entryRuntimeRequirements.has(
18561964
RuntimeGlobals.thisAsExports
@@ -1862,7 +1970,7 @@ class JavascriptModulesPlugin {
18621970
requireScopeUsed ||
18631971
entryRuntimeRequirements.has(RuntimeGlobals.exports)
18641972
) {
1865-
const exportsArg = i === 0 ? RuntimeGlobals.exports : "{}";
1973+
const exportsArg = i === 0 || merge ? target : "{}";
18661974
args.push("0", exportsArg);
18671975
if (requireScopeUsed) {
18681976
args.push(RuntimeGlobals.require);
@@ -1874,7 +1982,7 @@ class JavascriptModulesPlugin {
18741982
if (needThisAsExports) {
18751983
const comma = args.length ? "," : "";
18761984
return `__webpack_modules__[${moduleIdExpr}].call(${
1877-
RuntimeGlobals.exports
1985+
merge ? target : RuntimeGlobals.exports
18781986
}${comma}${args.join(",")});`;
18791987
}
18801988
return `__webpack_modules__[${moduleIdExpr}](${args.join(
@@ -1887,10 +1995,42 @@ class JavascriptModulesPlugin {
18871995
}
18881996
if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) {
18891997
buf2.push(
1890-
`${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
1998+
merge
1999+
? `${RuntimeGlobals.onChunksLoaded}();`
2000+
: `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
18912001
);
18922002
}
18932003
buf2.push(...renderAwaitedEntries(awaitedEntries));
2004+
// Every entry has run by now, and the getters below read through to
2005+
// whichever one provides each name.
2006+
if (merge) {
2007+
const { exports, namespace } = getMergedExports(
2008+
/** @type {Module[]} */ (mergedModules),
2009+
moduleGraph,
2010+
chunk.runtime
2011+
);
2012+
buf2.push(
2013+
`${runtimeTemplate.renderLet()} ${RuntimeGlobals.exports} = {};`
2014+
);
2015+
if (namespace) {
2016+
buf2.push(
2017+
`${RuntimeGlobals.makeNamespaceObject}(${RuntimeGlobals.exports});`
2018+
);
2019+
}
2020+
if (exports.length > 0) {
2021+
const bindings = exports.map(
2022+
({ name, module, usedName }) =>
2023+
`${JSON.stringify(name)}, ${runtimeTemplate.returningFunction(
2024+
`${mergedTargets.get(module)}${propertyAccess([usedName])}`
2025+
)}`
2026+
);
2027+
buf2.push(
2028+
`${RuntimeGlobals.definePropertyGetters}(${
2029+
RuntimeGlobals.exports
2030+
}, [${bindings.join(", ")}]);`
2031+
);
2032+
}
2033+
}
18942034
if (
18952035
runtimeRequirements.has(RuntimeGlobals.startup) ||
18962036
(runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&

0 commit comments

Comments
 (0)