Skip to content

Commit

Permalink
fix(enhanced): refactor hoisting plugins (#3488)
Browse files Browse the repository at this point in the history
  • Loading branch information
ScriptedAlchemy authored Feb 11, 2025
1 parent 2b7ba18 commit 89d35b0
Show file tree
Hide file tree
Showing 18 changed files with 215 additions and 176 deletions.
1 change: 1 addition & 0 deletions .github/workflows/e2e-next-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ jobs:
- name: E2E Test for Next.js Dev
if: steps.check-ci.outcome == 'success'
run: |
npx kill-port 3000,3001,3002 &&
pnpm run app:next:dev &
sleep 1 &&
npx wait-on tcp:3001 &&
Expand Down
6 changes: 6 additions & 0 deletions apps/manifest-demo/3009-webpack-provider/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ module.exports = composePlugins(
config.watchOptions = {
ignored: ['**/node_modules/**', '**/@mf-types/**'],
};
config.devServer = {
...config.devServer,
devMiddleware: {
writeToDisk: true,
},
};
// publicPath must be specific url
config.output.publicPath = 'auto';
config.plugins.push(
Expand Down
1 change: 1 addition & 0 deletions apps/manifest-demo/webpack-host/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ module.exports = composePlugins(withNx(), withReact(), (config, context) => {
};
config.plugins.push(
new ModuleFederationPlugin({
runtime: false,
name: 'manifest_host',
remotes: {
remote1: 'webpack_provider@http://localhost:3009/mf-manifest.json',
Expand Down
1 change: 1 addition & 0 deletions apps/modernjs/modern.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export default defineConfig({

appendPlugins([
new ModuleFederationPlugin({
runtime: false,
name: 'app1',
exposes: {
'./thing': './src/test.ts',
Expand Down
24 changes: 12 additions & 12 deletions apps/modernjs/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
"targets": {
"build": {
"executor": "nx:run-commands",
"dependsOn": [
{
"target": "build",
"dependencies": true
}
],
"options": {
"dependsOn": [
{
"target": "build",
"dependencies": true
}
],
"commands": [
{
"command": "cd apps/modernjs; pnpm run build",
Expand All @@ -25,13 +25,13 @@
},
"serve": {
"executor": "nx:run-commands",
"dependsOn": [
{
"target": "build",
"dependencies": true
}
],
"options": {
"dependsOn": [
{
"target": "build",
"dependencies": true
}
],
"commands": [
{
"command": "cd apps/modernjs; pnpm run dev",
Expand Down
93 changes: 0 additions & 93 deletions apps/node-host/src/bootstrap.js
Original file line number Diff line number Diff line change
@@ -1,93 +0,0 @@
/**
* This is not a production server yet!
* This is only a minimal backend to get started.
*/

import express from 'express';
import * as path from 'path';
import node_local_remote from 'node_local_remote/test';
import { registerRemotes, loadRemote } from '@module-federation/runtime';

registerRemotes([
{
name: 'node_dynamic_remote',
entry: 'http://localhost:3026/remoteEntry.js',
},
]);

const getMemoryUsage = () => {
const formatSize = (bytes) => `${(bytes / 1024 / 1024).toFixed(2)} MB`;

const memory = process.memoryUsage();
return `Time: ${new Date()}\nheap total: ${formatSize(
memory.heapTotal,
)} heapUsed: ${formatSize(memory.heapUsed)} rss: ${formatSize(memory.rss)}`;
};

const remoteMsg = import('node_remote/test').then((m) => {
console.log('\x1b[32m%s\x1b[0m', m.default || m);
return m.default || m;
});
console.log('\x1b[32m%s\x1b[0m', node_local_remote);

const app = express();

app.use('/assets', express.static(path.join(__dirname, 'assets')));

app.get('/api', async (req, res) => {
res.send({
message: 'Welcome to node-host!',
remotes: {
// node_remote: await remoteMsg,
// node_local_remote,
},
});
});

app.get('/dynamic-remote', async (req, res) => {
const dynamicRemote = await loadRemote('node_dynamic_remote/test-with-axios');

res.send({
message: 'dynamic remote',
dynamicRemote: dynamicRemote(),
});
});

app.get('/upgrade-remote', async (req, res) => {
registerRemotes(
[
{
name: 'node_dynamic_remote',
entry: 'http://localhost:3027/remoteEntry.js',
},
],
{ force: true },
);

res.send({
message: 'Upgrade success!',
});
});

app.get('/memory-cache', async (req, res) => {
const memoryUsage = getMemoryUsage();
console.log(memoryUsage);
res.send({
message: 'memory-cache',
memoryUsage: memoryUsage,
});
});

app.get('/federation-info', async (req, res) => {
console.log(global.__FEDERATION__);
console.log(global.__FEDERATION__.__INSTANCES__[0].moduleCache);
res.send({
message: 'federation info will be output in terminal !',
});
});

const port = process.env.PORT || 3333;
const server = app.listen(port, () => {
console.log(`Listening at http://localhost:${port}/api`);
});
server.on('error', console.error);
94 changes: 93 additions & 1 deletion apps/node-host/src/main.js
Original file line number Diff line number Diff line change
@@ -1 +1,93 @@
import('./bootstrap');
/**
* This is not a production server yet!
* This is only a minimal backend to get started.
*/

import express from 'express';
import * as path from 'path';
import node_local_remote from 'node_local_remote/test';
import { registerRemotes, loadRemote } from '@module-federation/runtime';

registerRemotes([
{
name: 'node_dynamic_remote',
entry: 'http://localhost:3026/remoteEntry.js',
},
]);

const getMemoryUsage = () => {
const formatSize = (bytes) => `${(bytes / 1024 / 1024).toFixed(2)} MB`;

const memory = process.memoryUsage();
return `Time: ${new Date()}\nheap total: ${formatSize(
memory.heapTotal,
)} heapUsed: ${formatSize(memory.heapUsed)} rss: ${formatSize(memory.rss)}`;
};

const remoteMsg = import('node_remote/test').then((m) => {
console.log('\x1b[32m%s\x1b[0m', m.default || m);
return m.default || m;
});
console.log('\x1b[32m%s\x1b[0m', node_local_remote);

const app = express();

app.use('/assets', express.static(path.join(__dirname, 'assets')));

app.get('/api', async (req, res) => {
res.send({
message: 'Welcome to node-host!',
remotes: {
node_remote: await remoteMsg,
node_local_remote,
},
});
});

app.get('/dynamic-remote', async (req, res) => {
const dynamicRemote = await loadRemote('node_dynamic_remote/test-with-axios');

res.send({
message: 'dynamic remote',
dynamicRemote: dynamicRemote(),
});
});

app.get('/upgrade-remote', async (req, res) => {
registerRemotes(
[
{
name: 'node_dynamic_remote',
entry: 'http://localhost:3027/remoteEntry.js',
},
],
{ force: true },
);

res.send({
message: 'Upgrade success!',
});
});

app.get('/memory-cache', async (req, res) => {
const memoryUsage = getMemoryUsage();
console.log(memoryUsage);
res.send({
message: 'memory-cache',
memoryUsage: memoryUsage,
});
});

app.get('/federation-info', async (req, res) => {
console.log(global.__FEDERATION__);
console.log(global.__FEDERATION__.__INSTANCES__[0].moduleCache);
res.send({
message: 'federation info will be output in terminal !',
});
});

const port = process.env.PORT || 3333;
const server = app.listen(port, () => {
console.log(`Listening at http://localhost:${port}/api`);
});
server.on('error', console.error);
6 changes: 3 additions & 3 deletions apps/node-host/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ module.exports = composePlugins(withNx(), async (config) => {
runtimePlugins: [
require.resolve('@module-federation/node/runtimePlugin'),
],
experiments: {
asyncStartup: true,
},
remotes: {
node_local_remote:
'commonjs ../../node-local-remote/dist/remoteEntry.js',
// node_local_remote: '__webpack_require__.federation.instance.moduleCache.get("node_local_remote")',
// node_remote:
// '__webpack_require__.federation.instance.moduleCache.get("node_remote")@http://localhost:3002/remoteEntry.js',
node_remote: 'node_remote@http://localhost:3022/remoteEntry.js',
},
}),
Expand Down
4 changes: 1 addition & 3 deletions packages/enhanced/src/lib/container/ContainerPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,6 @@ class ContainerPlugin {
compilation: Compilation,
callback: (error?: WebpackError | null | undefined) => void,
) => {
const hasSingleRuntimeChunk =
compilation.options?.optimization?.runtimeChunk;
const hooks = FederationModulesPlugin.getCompilationHooks(compilation);
const federationRuntimeDependency =
federationRuntimePluginInstance.getDependency(compiler);
Expand All @@ -215,7 +213,7 @@ class ContainerPlugin {
{
name,
filename,
runtime: hasSingleRuntimeChunk ? false : runtime,
runtime,
library,
},
(error: WebpackError | null | undefined) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,16 @@ class EmbedFederationRuntimeModule extends RuntimeModule {

const result = Template.asString([
`var oldStartup = ${RuntimeGlobals.startup};`,
`var hasRun = false;`,
`${RuntimeGlobals.startup} = ${compilation.runtimeTemplate.basicFunction(
'',
[`${initRuntimeModuleGetter};`, `return oldStartup();`],
[
`if (!hasRun) {`,
` hasRun = true;`,
` ${initRuntimeModuleGetter};`,
`}`,
`return oldStartup();`,
],
)};`,
]);
this._cachedGeneratedCode = result;
Expand Down
Loading

0 comments on commit 89d35b0

Please sign in to comment.