Skip to content
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

fix(rspack_plugin_mf): add chunk js matcher runtime to federation runtime #6434

Merged
merged 6 commits into from
May 9, 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 8 additions & 7 deletions crates/rspack_plugin_mf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_hash = { path = "../rspack_hash" }
rspack_hook = { path = "../rspack_hook" }
rspack_identifier = { path = "../rspack_identifier" }
rspack_loader_runner = { path = "../rspack_loader_runner" }
rspack_util = { path = "../rspack_util" }
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_hash = { path = "../rspack_hash" }
rspack_hook = { path = "../rspack_hook" }
rspack_identifier = { path = "../rspack_identifier" }
rspack_loader_runner = { path = "../rspack_loader_runner" }
rspack_plugin_runtime = { path = "../rspack_plugin_runtime" }
rspack_util = { path = "../rspack_util" }

async-trait = { workspace = true }
hashlink = { workspace = true }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use async_trait::async_trait;
use rspack_core::{
impl_runtime_module,
compile_boolean_matcher, impl_runtime_module,
rspack_sources::{BoxSource, RawSource, SourceExt},
ApplyContext, ChunkUkey, Compilation, CompilationAdditionalTreeRuntimeRequirements,
CompilerOptions, Plugin, PluginContext, RuntimeGlobals, RuntimeModule, RuntimeModuleStage,
ApplyContext, BooleanMatcher, Chunk, ChunkUkey, Compilation,
CompilationAdditionalTreeRuntimeRequirements, CompilerOptions, Plugin, PluginContext,
RuntimeGlobals, RuntimeModule, RuntimeModuleStage,
};
use rspack_error::Result;
use rspack_hook::{plugin, plugin_hook};
use rspack_identifier::Identifier;
use rspack_plugin_runtime::chunk_has_js;
use rspack_util::source_map::SourceMapKind;

#[impl_runtime_module]
#[derive(Debug, Eq)]
pub struct FederationRuntimeModule {
Expand Down Expand Up @@ -41,20 +42,46 @@ impl RuntimeModule for FederationRuntimeModule {
RuntimeModuleStage::Normal
}

fn generate(&self, _: &Compilation) -> rspack_error::Result<BoxSource> {
Ok(RawSource::from(federation_runtime_template()).boxed())
fn generate(&self, compilation: &Compilation) -> rspack_error::Result<BoxSource> {
let chunk = compilation
.chunk_by_ukey
.expect_get(&self.chunk.expect("The chunk should be attached."));
Ok(RawSource::from(federation_runtime_template(chunk, compilation)).boxed())
}
}

fn federation_runtime_template() -> String {
fn federation_runtime_template(chunk: &Chunk, compilation: &Compilation) -> String {
let federation_global = format!("{}.federation", RuntimeGlobals::REQUIRE);

let condition_map =
compilation
.chunk_graph
.get_chunk_condition_map(&chunk.ukey, compilation, chunk_has_js);
let has_js_matcher = compile_boolean_matcher(&condition_map);

let chunk_matcher = if matches!(has_js_matcher, BooleanMatcher::Condition(false)) {
String::from("")
} else {
format!(
r#"
chunkMatcher: function(chunkId) {{
return {has_js_matcher};
}}
"#,
has_js_matcher = &has_js_matcher.render("chunkId")
)
};

format!(
r#"
if(!{federation_global}){{
{federation_global} = {{}};
{federation_global} = {{
{chunk_matcher}
}};
}}
"#,
federation_global = federation_global,
chunk_matcher = chunk_matcher
)
}

Expand Down
3 changes: 2 additions & 1 deletion crates/rspack_plugin_runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ mod import_scripts_chunk_loading;
pub use import_scripts_chunk_loading::ImportScriptsChunkLoadingPlugin;
mod runtime_module;
pub use runtime_module::{
chunk_has_css, is_enabled_for_chunk, stringify_chunks, GetChunkFilenameRuntimeModule,
chunk_has_css, chunk_has_js, is_enabled_for_chunk, stringify_chunks,
GetChunkFilenameRuntimeModule,
};
mod startup_chunk_dependencies;
pub use startup_chunk_dependencies::StartupChunkDependenciesPlugin;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from "react";

export default () => {
return `App fetched with Chunk Handler __HANDLER__`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from "react";

export default () => {
return `ComponentB rendered with [${React()}]`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import React from "react";
import ComponentA from "containerA/ComponentA";

export default () => {
return `ComponentC rendered with [${React()}] and [${ComponentA()}]`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
it("should load chunk with patched chunk handler", () => {
return import("./App").then(({ default: App }) => {
const rendered = App();
console.log(rendered)
expect(rendered).toBe(
"App fetched with Chunk Handler PASS"
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"private": true,
"engines": {
"node": ">=10.13.0"
},
"dependencies": {
"react": "*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const runtimePlugin = function () {
return {
name: 'my-runtime-plugin',
beforeInit(args) {

const federationWarehouse = __webpack_require__.federation
!function() {
var installedChunks = {"115": 0,};
var installChunk = function (chunk) {
var moreModules = chunk.modules, chunkIds = chunk.ids,
runtime = chunk.runtime;
for (var moduleId in moreModules) {
if (__webpack_require__.o(moreModules, moduleId)) {
__webpack_require__.m[moduleId] = moreModules[moduleId];
}
}
if (runtime) runtime(__webpack_require__);
for (var i = 0; i < chunkIds.length; i++) {
if (installedChunks[chunkIds[i]]) {
installedChunks[chunkIds[i]][0]();
}
installedChunks[chunkIds[i]] = 0;
}

};

// ReadFile + VM.run chunk loading for javascript"
const handler = function (chunkId, promises) {
var installedChunkData = installedChunks[chunkId];
if (installedChunkData !== 0) { // 0 means "already installed".
// array of [resolve, reject, promise] means "currently loading"
if (installedChunkData) {
promises.push(installedChunkData[2]);
} else {
if (__webpack_require__.federation.chunkMatcher(chunkId)) { // all chunks have JS
// load the chunk and return promise to it
var promise

promise = new Promise(function (resolve, reject) {
installedChunkData = installedChunks[chunkId] = [resolve, reject];
var filename = __non_webpack_require__('path').join(
__dirname, "" + __webpack_require__.u(chunkId));
__non_webpack_require__('fs').readFile(filename, 'utf-8', function (err, content) {
if (err) return reject(err);
var chunk = {};
content = content.replace('__HANDLER__', 'PASS')
__non_webpack_require__('vm').runInThisContext(
'(function(exports, require, __dirname, __filename) {' +
content + '\n})',
filename)(
chunk, __non_webpack_require__, __non_webpack_require__('path').dirname(filename), filename);
installChunk(chunk);
});
});

promises.push(installedChunkData[2] = promise);
} else installedChunks[chunkId] = 0;

}
}

};
if(!__webpack_require__.f.j) {
__webpack_require__.f.j = handler
} else {
__webpack_require__.f.readfileVm = handler
}

}();
console.log('beforeInit: ', args);
return args;
},
beforeRequest(args) {
console.log('beforeRequest: ', args);
return args;
},
afterResolve(args) {
console.log('afterResolve', args);
return args;
},
onLoad(args) {
console.log('onLoad: ', args);
return args;
},
async loadShare(args) {
console.log('loadShare:', args);
},
async beforeLoadShare(args) {
console.log('beforeloadShare:', args);
return args;
},
};
};
export default runtimePlugin;
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// eslint-disable-next-line node/no-unpublished-require
const { ModuleFederationPlugin } = require("@rspack/core").container;

const common = {
entry: {
main: "./index.js"
},
target: 'async-node',
optimization: {
runtimeChunk: "single"
}
};

/** @type {ConstructorParameters<typeof ModuleFederationPlugin>[0]} */
const commonMF = {
runtime: false,
exposes: {
"./ComponentB": "./ComponentB",
"./ComponentC": "./ComponentC"
},
shared: ["react"]
};

/** @type {import("@rspack/core").Configuration[]} */
module.exports = [
{
...common,
output: {
filename: "[name].js",
uniqueName: "1-container-full"
},
plugins: [
new ModuleFederationPlugin({
name: "container",
library: { type: "commonjs-module" },
runtimePlugins: [require.resolve('./runtimePlugin.js')],
filename: "container.js",
remotes: {
containerA: "../0-container-full/container.js",
},
...commonMF
})
]
}
];
Loading