fix: improve `module.exports` bundle to ESM library (#19776)

This commit is contained in:
hai-x 2025-08-11 19:55:26 +08:00 committed by GitHub
parent 59a645cdf8
commit e3c48f5df4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 52 additions and 2 deletions

View File

@ -8,6 +8,7 @@
const { ConcatSource } = require("webpack-sources");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
const CommonJsSelfReferenceDependency = require("../dependencies/CommonJsSelfReferenceDependency");
const ConcatenatedModule = require("../optimize/ConcatenatedModule");
const propertyAccess = require("../util/propertyAccess");
const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
@ -104,6 +105,17 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin {
{ options, compilation }
) {
const result = new ConcatSource(source);
if (!module.buildMeta || !module.buildMeta.exportsType) {
for (const dependency of module.dependencies) {
if (dependency instanceof CommonJsSelfReferenceDependency) {
result.add(`export { ${RuntimeGlobals.exports} as default }`);
break;
}
}
return result;
}
const exportsInfo = options.export
? [
moduleGraph.getExportInfo(

View File

@ -1,6 +1,5 @@
it("should have the hoisted container references", async () => {
const before = __webpack_modules__;
debugger;
// Initialize tracker array
const tracker = [];
@ -12,7 +11,6 @@ it("should have the hoisted container references", async () => {
await Promise.all(tracker);
const after = __webpack_modules__;
debugger;
// Verify that tracker contains hoisted container references
expect(tracker).not.toHaveLength(0);

View File

@ -802,5 +802,18 @@ module.exports = (env, { testPath }) => [
"external-named": "./non-external-named"
}
}
},
{
entry: "./class-commonjs",
output: {
filename: "commonjs-bundle-to-esm.mjs",
module: true,
library: {
type: "module"
}
},
experiments: {
outputModule: true
}
}
];

View File

@ -0,0 +1,8 @@
import library from "library";
it(
"should be able to import harmony exports from library (" + NAME + ")",
function () {
expect(new library().getNumber()).toBe(1);
}
);

View File

@ -687,5 +687,24 @@ module.exports = (env, { testPath }) => [
NAME: JSON.stringify("entryC")
})
]
},
{
entry: "./esm-with-bundled-commonjs",
output: {
module: true
},
experiments: { outputModule: true },
externals: {
library: path.resolve(
testPath,
"../0-create-library/commonjs-bundle-to-esm.mjs"
)
},
externalsType: "module-import",
plugins: [
new webpack.DefinePlugin({
NAME: JSON.stringify("commonjs-bundle-to-esm")
})
]
}
];