Skip to content

fix(modern-module): compat with more export cases #7394

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions crates/rspack_plugin_library/src/modern_module_library_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ use std::hash::Hash;

use rspack_core::rspack_sources::{ConcatSource, RawSource, SourceExt};
use rspack_core::{
merge_runtime, ApplyContext, ChunkUkey, CodeGenerationExportsFinalNames, Compilation,
CompilationOptimizeChunkModules, CompilationParams, CompilerCompilation, CompilerOptions,
ConcatenatedModule, ConcatenatedModuleExportsDefinitions, LibraryOptions, ModuleIdentifier,
Plugin, PluginContext,
merge_runtime, to_identifier, ApplyContext, ChunkUkey, CodeGenerationExportsFinalNames,
Compilation, CompilationOptimizeChunkModules, CompilationParams, CompilerCompilation,
CompilerOptions, ConcatenatedModule, ConcatenatedModuleExportsDefinitions, LibraryOptions,
ModuleIdentifier, Plugin, PluginContext,
};
use rspack_error::{error_bail, Result};
use rspack_hash::RspackHash;
Expand Down Expand Up @@ -74,6 +74,14 @@ impl ModernModuleLibraryPlugin {
let unconcatenated_module_ids = module_ids
.iter()
.filter(|id| !concatenated_module_ids.contains(id))
.filter(|id| {
let module = module_graph
.module_by_identifier(id)
.expect("should have module");
module
.get_concatenation_bailout_reason(&module_graph, &compilation.chunk_graph)
.is_none()
})
.collect::<HashSet<_>>();

for module_id in unconcatenated_module_ids.into_iter() {
Expand Down Expand Up @@ -114,6 +122,7 @@ fn render_startup(
.get(module_id, Some(&chunk.runtime));

let mut exports = vec![];
let mut exports_with_property_access = vec![];

let Some(_) = self.get_options_for_chunk(compilation, chunk_ukey)? else {
return Ok(());
Expand All @@ -136,14 +145,29 @@ fn render_startup(
.expect("name can't be empty");

let final_name = exports_final_names.get(used_name.as_str());

if let Some(final_name) = final_name {
if info_name == final_name {
// Currently, there's not way to determine if a final_name contains a property access.
if final_name.contains('.') || final_name.contains("()") {
exports_with_property_access.push((final_name, info_name));
} else if info_name == final_name {
exports.push(info_name.to_string());
} else {
exports.push(format!("{} as {}", final_name, info_name));
}
}
}

for (final_name, info_name) in exports_with_property_access.iter() {
let var_name = format!("__webpack_exports__{}", to_identifier(info_name));

source.add(RawSource::from(format!(
"var {var_name} = {};\n",
final_name
)));

exports.push(format!("{} as {}", var_name, info_name));
}
}

if !exports.is_empty() {
Expand Down
119 changes: 99 additions & 20 deletions packages/rspack-test-tools/tests/__snapshots__/Config.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -327,20 +327,9 @@ div {
head{--webpack--120:&_13;}"
`;

exports[`config config/library/modern-module-force-concaten step should pass 1`] = `
"
;// CONCATENATED MODULE: ./a.js
const a = 'a'

export { a };
"
`;

exports[`config config/library/modern-module-force-concaten step should pass 2`] = `
exports[`config config/library/modern-module-force-concaten step should pass: .cjs should bail out 1`] = `
"var __webpack_modules__ = ({
\\"772\\": (function (module) {

;// CONCATENATED MODULE: ./b.cjs
\\"851\\": (function (module) {
module.exports = 'b'

}),
Expand Down Expand Up @@ -374,23 +363,113 @@ return module.exports;
// startup
// Load entry module and return exports
// This entry module is referenced by other modules so it can't be inlined
var __webpack_exports__ = __webpack_require__(\\"772\\");
var __webpack_exports__ = __webpack_require__(\\"851\\");
"
`;

exports[`config config/library/modern-module-force-concaten step should pass 3`] = `
"
;// CONCATENATED MODULE: ./c.js
const c = 'c'
exports[`config config/library/modern-module-force-concaten step should pass: .cjs should bail out when bundling 1`] = `
"var __webpack_modules__ = ({
\\"997\\": (function (module) {
module.exports = 'bar'

}),

});
/************************************************************************/
// The module cache
var __webpack_module_cache__ = {};

// The require function
function __webpack_require__(moduleId) {

// Check if module is in cache
var cachedModule = __webpack_module_cache__[moduleId];
if (cachedModule !== undefined) {
return cachedModule.exports;
}
// Create a new module (and put it into the cache)
var module = (__webpack_module_cache__[moduleId] = {
exports: {}
});
// Execute the module function
__webpack_modules__[moduleId](module, module.exports, __webpack_require__);

// Return the exports of the module
return module.exports;

}

/************************************************************************/
// webpack/runtime/compat_get_default_export
(() => {
// getDefaultExport function for compatibility with non-harmony modules
__webpack_require__.n = function (module) {
var getter = module && module.__esModule ?
function () { return module['default']; } :
function () { return module; };
__webpack_require__.d(getter, { a: getter });
return getter;
};




})();
// webpack/runtime/define_property_getters
(() => {
__webpack_require__.d = function(exports, definition) {
for(var key in definition) {
if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
}
}
};
})();
// webpack/runtime/has_own_property
(() => {
__webpack_require__.o = function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};

})();
/************************************************************************/

;// CONCATENATED MODULE: ./e/foo.js
const foo = 'foo'

// EXTERNAL MODULE: ./e/bar.cjs
var bar = __webpack_require__(\\"997\\");
var bar_default = /*#__PURE__*/__webpack_require__.n(bar);
;// CONCATENATED MODULE: ./e/index.js





var __webpack_exports__bar = (bar_default());
export { foo, __webpack_exports__bar as bar };
"
`;

exports[`config config/library/modern-module-force-concaten step should pass 4`] = `
exports[`config config/library/modern-module-force-concaten step should pass: .mjs should concat 1`] = `
"
;// CONCATENATED MODULE: ./d.mjs
const d = 'd'
export { d };
"
`;

exports[`config config/library/modern-module-force-concaten step should pass: harmony export should concat 1`] = `
"
;// CONCATENATED MODULE: ./a.js
const a = 'a'

export { a };
"
`;

exports[`config config/library/modern-module-force-concaten step should pass: unambiguous should bail out 1`] = `
"const c = 'c'

"
`;

Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const d = 'd'
const d = 'd'
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = 'bar'
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const foo = 'foo'
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { foo } from './foo.js'
import bar from './bar.cjs'

export { foo, bar }
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ module.exports = {
"a": "./a.js",
"b": "./b.cjs",
"c": "./c.js",
"d": "./d.mjs"
"d": "./d.mjs",
"e": "./e/index.js"
},
output: {
filename: `[name].js`,
Expand All @@ -13,15 +14,6 @@ module.exports = {
iife: false,
chunkFormat: "module",
},
externalsType: "module",
externals: [
(data, callback) => {
if (data.contextInfo.issuer) {
return callback(null, data.request)
}
callback()
},
],
experiments: {
outputModule: true
},
Expand All @@ -37,10 +29,11 @@ module.exports = {
*/
const handler = compilation => {
compilation.hooks.afterProcessAssets.tap("testcase", assets => {
expect(assets['a.js']._value).toMatchSnapshot();
expect(assets['b.js']._value).toMatchSnapshot();
expect(assets['c.js']._value).toMatchSnapshot();
expect(assets['d.js']._value).toMatchSnapshot();
expect(assets['a.js']._value).toMatchSnapshot("harmony export should concat");
expect(assets['b.js']._value).toMatchSnapshot(".cjs should bail out");
expect(assets['c.js']._value).toMatchSnapshot("unambiguous should bail out");
expect(assets['d.js']._value).toMatchSnapshot(".mjs should concat");
expect(assets['e.js']._value).toMatchSnapshot(".cjs should bail out when bundling");
});
};
this.hooks.compilation.tap("testcase", handler);
Expand Down
Loading