Skip to content

Commit c23dcff

Browse files
fix: expose exports of all entry modules in library output
When an entry is an array of modules and a library output is configured, only the exports of the last entry module were flagged as used and exposed on the library. Exports of all earlier entry modules were tree-shaken away and silently dropped. The fix stays entirely in the library plugin layer: - AbstractLibraryPlugin gains an opt-in finishAllEntryModules mode that flags the exports of every entry dependency as used, and a helper that renders startup code merging the exports of all entry modules of the chunk into the final library exports object. Later entry modules win on export name conflicts, preserving the documented last-entry-wins semantics. Merging is skipped when startup is delayed by depending chunks or when entry modules are inlined. - AssignLibraryPlugin (var, assign, this, window, self, global, commonjs, commonjs2) and ExportPropertyLibraryPlugin (amd, umd, system, jsonp) opt in. - module/modern-module and commonjs-static keep their current behavior, since their export lists are generated statically from the last entry module. Fixes #15936
1 parent 3cb8578 commit c23dcff

7 files changed

Lines changed: 172 additions & 18 deletions

File tree

‎lib/library/AbstractLibraryPlugin.js‎

Lines changed: 114 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"use strict";
77

88
const RuntimeGlobals = require("../RuntimeGlobals");
9+
const Template = require("../Template");
910
const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin");
1011

1112
/** @typedef {import("webpack-sources").Source} Source */
@@ -40,6 +41,7 @@ const COMMON_LIBRARY_NAME_MESSAGE =
4041
* @typedef {object} AbstractLibraryPluginOptions
4142
* @property {string} pluginName name of the plugin
4243
* @property {LibraryType} type used library type
44+
* @property {boolean=} finishAllEntryModules when true, finishEntryModule is called for every entry dependency instead of only the last one, so exports of all entry modules survive optimization
4345
*/
4446

4547
/**
@@ -51,11 +53,13 @@ class AbstractLibraryPlugin {
5153
* Creates an instance of AbstractLibraryPlugin.
5254
* @param {AbstractLibraryPluginOptions} options options
5355
*/
54-
constructor({ pluginName, type }) {
56+
constructor({ pluginName, type, finishAllEntryModules }) {
5557
/** @type {AbstractLibraryPluginOptions["pluginName"]} */
5658
this._pluginName = pluginName;
5759
/** @type {AbstractLibraryPluginOptions["type"]} */
5860
this._type = type;
61+
/** @type {boolean} */
62+
this._finishAllEntryModules = finishAllEntryModules || false;
5963
/** @type {WeakMap<LibraryOptions, T>} */
6064
this._parseCache = new WeakMap();
6165
}
@@ -84,8 +88,10 @@ class AbstractLibraryPlugin {
8488
: compilation.outputOptions.library
8589
);
8690
if (options !== false) {
87-
const dep = deps[deps.length - 1];
88-
if (dep) {
91+
const relevantDeps = this._finishAllEntryModules
92+
? deps
93+
: deps.slice(-1);
94+
for (const dep of relevantDeps) {
8995
const module = compilation.moduleGraph.getModule(dep);
9096
if (module) {
9197
this.finishEntryModule(module, name, {
@@ -150,6 +156,21 @@ class AbstractLibraryPlugin {
150156
});
151157
}
152158

159+
if (this._finishAllEntryModules) {
160+
hooks.inlineInRuntimeBailout.tap(_pluginName, (module, context) => {
161+
const options = getOptionsForChunk(context.chunk);
162+
if (options === false) return;
163+
if (
164+
this._getMergeableEntryModules(
165+
compilation.chunkGraph,
166+
context.chunk
167+
).length > 0
168+
) {
169+
return "the exports of multiple entry modules are merged into the library export";
170+
}
171+
});
172+
}
173+
153174
if (
154175
this.embedInRuntimeBailout !==
155176
AbstractLibraryPlugin.prototype.embedInRuntimeBailout
@@ -263,6 +284,96 @@ class AbstractLibraryPlugin {
263284
*/
264285
finishEntryModule(module, entryName, libraryContext) {}
265286

287+
/**
288+
* Get all javascript entry modules of a chunk that can take part in
289+
* merging exports into the library exports object. Returns an empty array
290+
* when merging is not applicable (single entry, or an entry depends on
291+
* other chunks so startup is delayed).
292+
* @param {ChunkGraph} chunkGraph the chunk graph
293+
* @param {Chunk} chunk the chunk
294+
* @returns {Module[]} the entry modules
295+
*/
296+
_getMergeableEntryModules(chunkGraph, chunk) {
297+
/** @type {Module[]} */
298+
const entries = [];
299+
for (const [
300+
module,
301+
entrypoint
302+
] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) {
303+
if (!chunkGraph.getModuleSourceTypes(module).has("javascript")) continue;
304+
if (entrypoint && entrypoint.chunks.some((c) => c !== chunk)) {
305+
// entry depends on other chunks, startup is delayed and
306+
// exports are not synchronously available for merging
307+
return [];
308+
}
309+
entries.push(module);
310+
}
311+
return entries.length > 1 ? entries : [];
312+
}
313+
314+
/**
315+
* Render code that merges the exports of all entry modules of the chunk
316+
* into the final library exports object. Returns an empty string when the
317+
* chunk has fewer than two mergeable entry modules. Later entry modules
318+
* override earlier ones on export name conflicts, which keeps the
319+
* documented "last entry wins" semantics for conflicting names.
320+
* @param {StartupRenderContext} renderContext render context
321+
* @returns {string} the merge code or an empty string
322+
*/
323+
_renderEntryExportsMerge(renderContext) {
324+
const { chunk, chunkGraph, inlined } = renderContext;
325+
if (inlined) return "";
326+
const entries = this._getMergeableEntryModules(chunkGraph, chunk);
327+
if (entries.length === 0) return "";
328+
const buf = [
329+
"// merge exports of all entry modules into the library exports object",
330+
"// entries are merged in reverse order and existing keys are skipped,",
331+
"// so later entry modules win on export name conflicts",
332+
"var __webpack_exports_merged__ = {};",
333+
"var __webpack_merge_entry__ = function (exports) {",
334+
Template.indent([
335+
"for (var key in exports) {",
336+
Template.indent([
337+
"if (Object.prototype.hasOwnProperty.call(exports, key) && !Object.prototype.hasOwnProperty.call(__webpack_exports_merged__, key)) {",
338+
Template.indent(
339+
"Object.defineProperty(__webpack_exports_merged__, key, Object.getOwnPropertyDescriptor(exports, key));"
340+
),
341+
"}"
342+
]),
343+
"}"
344+
]),
345+
"};"
346+
];
347+
buf.push(`__webpack_merge_entry__(${RuntimeGlobals.exports});`);
348+
for (const module of entries.slice(0, -1).reverse()) {
349+
buf.push(
350+
`__webpack_merge_entry__(${RuntimeGlobals.require}(${JSON.stringify(
351+
chunkGraph.getModuleId(module)
352+
)}));`
353+
);
354+
}
355+
buf.push(
356+
`if (${RuntimeGlobals.exports}.__esModule) ${RuntimeGlobals.makeNamespaceObject}(__webpack_exports_merged__);`
357+
);
358+
buf.push(`${RuntimeGlobals.exports} = __webpack_exports_merged__;`);
359+
return `${Template.asString(buf)}\n`;
360+
}
361+
362+
/**
363+
* Add the runtime requirements needed by the entry exports merge code
364+
* when the chunk has multiple mergeable entry modules.
365+
* @param {Chunk} chunk the chunk
366+
* @param {RuntimeRequirements} set runtime requirements
367+
* @param {ChunkGraph} chunkGraph the chunk graph
368+
* @returns {void}
369+
*/
370+
_addEntryExportsMergeRuntimeRequirements(chunk, set, chunkGraph) {
371+
if (this._getMergeableEntryModules(chunkGraph, chunk).length > 0) {
372+
set.add(RuntimeGlobals.require);
373+
set.add(RuntimeGlobals.makeNamespaceObject);
374+
}
375+
}
376+
266377
/**
267378
* Embed in runtime bailout.
268379
* @param {Module} module the exporting entry module

‎lib/library/AssignLibraryPlugin.js‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,10 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
132132
constructor(options) {
133133
super({
134134
pluginName: "AssignLibraryPlugin",
135-
type: options.type
135+
type: options.type,
136+
// "static" enumerates the exports of the last entry module at
137+
// compile time, so merging all entry exports is not applicable
138+
finishAllEntryModules: options.unnamed !== "static"
136139
});
137140
/** @type {AssignLibraryPluginOptions["prefix"]} */
138141
this.prefix = options.prefix;
@@ -315,18 +318,18 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
315318
* @param {LibraryContext<T>} libraryContext context
316319
* @returns {Source} source with library export
317320
*/
318-
renderStartup(
319-
source,
320-
module,
321-
{ moduleGraph, chunk },
322-
{ options, compilation }
323-
) {
321+
renderStartup(source, module, renderContext, { options, compilation }) {
322+
const { moduleGraph, chunk } = renderContext;
324323
const fullNameResolved = this._getResolvedFullName(
325324
options,
326325
chunk,
327326
compilation
328327
);
329328
const staticExports = this.unnamed === "static";
329+
if (!staticExports) {
330+
const merge = this._renderEntryExportsMerge(renderContext);
331+
if (merge) source = new ConcatSource(source, merge);
332+
}
330333
const exportAccess = options.export
331334
? propertyAccess(
332335
Array.isArray(options.export) ? options.export : [options.export]
@@ -430,6 +433,13 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
430433
*/
431434
runtimeRequirements(chunk, set, libraryContext) {
432435
set.add(RuntimeGlobals.exports);
436+
if (this.unnamed !== "static") {
437+
this._addEntryExportsMergeRuntimeRequirements(
438+
chunk,
439+
set,
440+
libraryContext.chunkGraph
441+
);
442+
}
433443
}
434444

435445
/**

‎lib/library/ExportPropertyLibraryPlugin.js‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin {
5050
constructor({ type }) {
5151
super({
5252
pluginName: "ExportPropertyLibraryPlugin",
53-
type
53+
type,
54+
finishAllEntryModules: true
5455
});
5556
}
5657

@@ -102,6 +103,11 @@ class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin {
102103
*/
103104
runtimeRequirements(chunk, set, libraryContext) {
104105
set.add(RuntimeGlobals.exports);
106+
this._addEntryExportsMergeRuntimeRequirements(
107+
chunk,
108+
set,
109+
libraryContext.chunkGraph
110+
);
105111
}
106112

107113
/**
@@ -113,13 +119,14 @@ class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin {
113119
* @returns {Source} source with library export
114120
*/
115121
renderStartup(source, module, renderContext, { options }) {
116-
if (!options.export) return source;
117-
const postfix = `${RuntimeGlobals.exports} = ${
118-
RuntimeGlobals.exports
119-
}${propertyAccess(
120-
Array.isArray(options.export) ? options.export : [options.export]
121-
)};\n`;
122-
return new ConcatSource(source, postfix);
122+
const merge = this._renderEntryExportsMerge(renderContext);
123+
const postfix = options.export
124+
? `${RuntimeGlobals.exports} = ${RuntimeGlobals.exports}${propertyAccess(
125+
Array.isArray(options.export) ? options.export : [options.export]
126+
)};\n`
127+
: "";
128+
if (!merge && !postfix) return source;
129+
return new ConcatSource(source, merge, postfix);
123130
}
124131
}
125132

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const fromA = "a";
2+
export const shared = "from-a";
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const fromB = "b";
2+
export const shared = "from-b";
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
export const fromIndex = "index";
2+
3+
it("should expose exports of all entry modules in the library (issue 15936)", () => {
4+
expect(MultiEntryLib.fromA).toBe("a");
5+
expect(MultiEntryLib.fromB).toBe("b");
6+
expect(MultiEntryLib.fromIndex).toBe("index");
7+
});
8+
9+
it("should let later entry modules win on export name conflicts", () => {
10+
expect(MultiEntryLib.shared).toBe("from-b");
11+
});
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration} */
4+
module.exports = {
5+
entry: {
6+
main: ["./a.js", "./b.js", "./index.js"]
7+
},
8+
output: {
9+
library: { name: "MultiEntryLib", type: "var" }
10+
}
11+
};

0 commit comments

Comments
 (0)