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

feat(enhanced): layers support in module code generation #3371

Merged
merged 2 commits into from
Dec 29, 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 packages/enhanced/src/lib/sharing/ProvideSharedModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ class ProvideSharedModule extends Module {
requiredVersion: this._requiredVersion,
strictVersion: this._strictVersion,
singleton: this._singleton,
layer: this.layer
},
});
return { sources, data, runtimeRequirements };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class ProvideSharedModuleFactory extends ModuleFactory {
dep.requiredVersion,
dep.strictVersion,
dep.singleton,
dep.layer
),
});
}
Expand Down
1 change: 1 addition & 0 deletions packages/enhanced/src/lib/sharing/ProvideSharedPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ class ProvideSharedPlugin {
config.requiredVersion!,
config.strictVersion!,
config.singleton!,
config.layer
),
{
name: undefined,
Expand Down
61 changes: 51 additions & 10 deletions packages/enhanced/src/lib/sharing/ShareRuntimeModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,14 @@ class ShareRuntimeModule extends RuntimeModule {
if (sharedOption) {
sharedInitOptions[sharedOption.name] =
sharedInitOptions[sharedOption.name] || [];
const isSameVersion = sharedInitOptions[sharedOption.name].find(
(s) => s.version === sharedOption.version,
const isSameVersionAndLayer = sharedInitOptions[
sharedOption.name
].find(
(s) =>
s.version === sharedOption.version &&
s.shareConfig?.layer === sharedOption.shareConfig?.layer,
);
if (!isSameVersion) {
if (!isSameVersionAndLayer) {
sharedInitOptions[sharedOption.name].push(sharedOption);
}
}
Expand All @@ -88,18 +92,19 @@ class ShareRuntimeModule extends RuntimeModule {
(sum, sharedName) => {
const sharedOptions = sharedInitOptions[sharedName];
let str = '';
sharedOptions.forEach((sharedOption) => {

// Ensure all options are included without filtering
sharedOptions.forEach((option) => {
str += `{${Template.indent([
`version: ${sharedOption.version},`,
`get: ${sharedOption.getter},`,
`scope: ${JSON.stringify(sharedOption.shareScope)},`,
`shareConfig: ${JSON.stringify(sharedOption.shareConfig)}`,
`version: ${option.version},`,
`get: ${option.getter},`,
`scope: ${JSON.stringify(option.shareScope)},`,
`shareConfig: ${JSON.stringify(option.shareConfig)}`,
])}},`;
});
str = `[${str}]`;

str = `[${str}]`;
sum += `${Template.indent([`"${sharedName}": ${str},`])}`;

return sum;
},
'',
Expand All @@ -108,6 +113,42 @@ class ShareRuntimeModule extends RuntimeModule {
const federationGlobal = getFederationGlobalScope(
RuntimeGlobals || ({} as typeof RuntimeGlobals),
);

// Group shared modules by scope and layer
const scopedModules = new Map<
string,
Map<string | undefined, Set<string>>
>();
for (const [scopeName, stages] of initCodePerScope) {
const layeredModules = new Map<string | undefined, Set<string>>();
scopedModules.set(scopeName, layeredModules);

for (const [, inits] of stages) {
for (const init of inits) {
const layer = init.match(/layer:\s*["']([^"']+)["']/)?.[1];
let moduleSet = layeredModules.get(layer);
if (!moduleSet) {
moduleSet = new Set();
layeredModules.set(layer, moduleSet);
}
moduleSet.add(init);
}
}
}

// Generate the registration code
const registrationCode = Array.from(scopedModules.entries())
.map(([scopeName, layeredModules]) => {
const cases = Array.from(layeredModules.entries())
.map(([layer, inits]) => {
const initCode = Array.from(inits).join('\n');
return `case "${scopeName}": {\n${Template.indent(initCode)}\n}`;
})
.join('\nbreak;\n');
return cases;
})
.join('\n');

return Template.asString([
`${getFederationGlobalScope(
RuntimeGlobals,
Expand Down
4 changes: 3 additions & 1 deletion packages/enhanced/src/lib/sharing/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/

import { isRequiredVersion } from '@module-federation/sdk';
import type { ConsumeOptions } from 'webpack/lib/sharing/ConsumeSharedModule';
import type { ConsumeOptions } from '../../declarations/plugins/sharing/ConsumeSharedModule';
import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';
import type { InputFileSystem } from 'webpack/lib/util/fs';
const { join, dirname, readJson } = require(
Expand Down Expand Up @@ -459,6 +459,7 @@ export function normalizeConsumeShareOptions(consumeOptions: ConsumeOptions) {
eager,
shareKey,
shareScope,
layer,
} = consumeOptions;
return {
shareConfig: {
Expand All @@ -467,6 +468,7 @@ export function normalizeConsumeShareOptions(consumeOptions: ConsumeOptions) {
strictVersion,
singleton,
eager,
layer,
},
shareScope,
shareKey,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import React from 'react';
import ComponentA from 'containerA/ComponentA';
import ComponentALayers from 'containerA/ComponentALayers';

export default () => {
return `App rendered with [${React()}], [${ComponentA()}] and [${ComponentALayers()}]`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from 'react';

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

export default () => {
debugger;
return `ComponentALayers rendered with [${React.layeredComponentsReact()}]`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
it('should load the component from container', () => {
return import('./App').then(({ default: App }) => {
const rendered = App();
expect(rendered).toBe(
'App rendered with [This is react 0.1.2], [ComponentA rendered with [This is react 0.1.2]] and [ComponentALayers rendered with [This is layered react]]',
);
return import('./upgrade-react').then(({ default: upgrade }) => {
upgrade();
const rendered = App();
expect(rendered).toBe(
'App rendered with [This is react 1.2.3], [ComponentA rendered with [This is react 1.2.3]] and [ComponentALayers rendered with [This is layered react]]',
);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = function (source) {
console.log(source);
return source.replace('__PLACEHOLDER__', 'This is layered react');
};

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "3-layers-full",
"version": "1.0.0",
"private": true,
"scripts": {
"build": "webpack --config=webpack.config.js"
},
"dependencies": {
"react": "1.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
findBundle: function (i, options) {
return i === 0 ? './main.js' : './module/main.mjs';
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { setVersion } from 'react';

export default function upgrade() {
setVersion('1.2.3');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const { ModuleFederationPlugin } = require('../../../../dist/src');
const path = require('path');

const common = {
name: 'layer_container',
exposes: {
'./ComponentA': {
import: './ComponentA',
},
'./ComponentALayers': {
import: './ComponentALayers',
},
},
shared: {
react: {
version: false,
requiredVersion: false,
singleton: true,
},
'layered-react': {
request: 'react',
import: 'react',
shareKey: 'react',
version: false,
requiredVersion: false,
singleton: true,
layer: 'layered-components',
issuerLayer: 'layered-components',
},
},
};

const commonConfig = {
devtool: false,
experiments: {
layers: true,
},
entry: './index.js',
mode: 'development',
module: {
rules: [
{
test: /ComponentALayers\.js$/,
layer: 'layered-components',
},
{
test: /react$/,
issuerLayer: 'layered-components',
layer: 'layered-components',
use: [
{
loader: path.resolve(__dirname, './layered-react-loader.js'),
},
],
},
],
},
};

module.exports = [
{
...commonConfig,
output: {
filename: '[name].js',
uniqueName: '3-layers-full',
},
plugins: [
new ModuleFederationPlugin({
library: { type: 'commonjs-module' },
filename: 'container.js',
remotes: {
containerA: {
external: './container.js',
},
},
...common,
}),
],
},
{
...commonConfig,
experiments: {
...commonConfig.experiments,
outputModule: true,
},
output: {
filename: 'module/[name].mjs',
uniqueName: '3-layers-full-mjs',
},
plugins: [
new ModuleFederationPlugin({
library: { type: 'module' },
filename: 'module/container.mjs',
remotes: {
containerA: {
external: './container.mjs',
},
},
...common,
}),
],
target: 'node14',
},
];
10 changes: 10 additions & 0 deletions packages/enhanced/test/configCases/container/4-layers-full/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import React from 'react';
import ComponentA from 'containerA/ComponentA';
import ComponentB from 'containerB/ComponentB';
import LocalComponentB from './ComponentB';

export default () => {
return `App rendered with [${React()}] and [${ComponentA()}] and [${ComponentB()}]`;
};

expect(ComponentB).not.toBe(LocalComponentB);
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,7 @@
import React from 'react';
import ComponentA from 'containerA/ComponentA';
import ComponentB from 'containerB/ComponentB';

export default () => {
return `ComponentC rendered with [${React()}] and [${ComponentA()}] and [${ComponentB()}]`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
it('should load the component from container', () => {
return import('./App').then(({ default: App }) => {
const rendered = App();
expect(rendered).toBe(
'App rendered with [This is react 2.1.0] and [ComponentA rendered with [This is react 2.1.0]] and [ComponentB rendered with [This is react 2.1.0]]',
);
return import('./upgrade-react').then(({ default: upgrade }) => {
upgrade();
const rendered = App();
expect(rendered).toBe(
'App rendered with [This is react 3.2.1] and [ComponentA rendered with [This is react 3.2.1]] and [ComponentB rendered with [This is react 3.2.1]]',
);
});
});
});

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

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

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,5 @@
module.exports = {
findBundle: function (i, options) {
return i === 0 ? './main.js' : './module/main.mjs';
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { setVersion } from 'react';

export default function upgrade() {
setVersion('3.2.1');
}
Loading
Loading