Skip to content

docs: enhance dynamic-remotes example documentation and modernization guide #4360

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 15 commits into from
Aug 3, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
431 changes: 415 additions & 16 deletions advanced-api/dynamic-remotes/README.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions advanced-api/dynamic-remotes/app1/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"clean": "rm -rf dist"
},
"dependencies": {
"react": "^16.13.0",
"react-dom": "^16.13.0"
"react": "^18.3.1",
"react-dom": "^18.3.1"
}
}
21 changes: 15 additions & 6 deletions advanced-api/dynamic-remotes/app1/rspack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,23 @@ module.exports = {
// so it will always use the higher version found
shared: {
react: {
import: 'react', // the "react" package will be used a provided and fallback module
shareKey: 'react', // under this name the shared module will be placed in the share scope
shareScope: 'default', // share scope with this name will be used
singleton: true, // only a single version of the shared module is allowed
import: 'react',
shareKey: 'react',
shareScope: 'default',
singleton: true,
requiredVersion: '^18.3.1',
strictVersion: true,
},
'react/jsx-runtime': {
singleton: true,
},
'react/jsx-dev-runtime': {
singleton: true,
},
'react/jsx-dev-runtime': {},
'react-dom': {
singleton: true, // only a single version of the shared module is allowed
singleton: true,
requiredVersion: '^18.3.1',
strictVersion: true,
},
},
}),
Expand Down
174 changes: 166 additions & 8 deletions advanced-api/dynamic-remotes/app1/src/App.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,115 @@
import React, { useState, useEffect, Suspense } from 'react';
import { init, loadRemote } from '@module-federation/runtime';

class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}

static getDerivedStateFromError(error) {
return { hasError: true, error };
}

componentDidCatch(error, errorInfo) {
console.error('Remote component error:', error, errorInfo);
}

render() {
if (this.state.hasError) {
return (
<div style={{
padding: '2em',
border: '2px solid #ff6b6b',
borderRadius: '4px',
backgroundColor: '#ffe0e0',
color: '#c92a2a'
}}>
<h3>⚠️ Component Failed to Load</h3>
<p>Unable to load the remote component. Please try again or check the remote application.</p>
<details>
<summary>Error Details</summary>
<pre style={{ fontSize: '12px', overflow: 'auto' }}>
{this.state.error?.toString()}
</pre>
</details>
<button
onClick={() => this.setState({ hasError: false, error: null })}
style={{
marginTop: '1em',
padding: '0.5em 1em',
backgroundColor: '#c92a2a',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Retry
</button>
</div>
);
}

return this.props.children;
}
}

const getRemoteEntry = (port) => {
const baseUrl = process.env.NODE_ENV === 'production'
? (process.env.REACT_APP_REMOTE_BASE_URL || window.location.origin)
: 'http://localhost';
return `${baseUrl}:${port}/remoteEntry.js`;
Copy link
Preview

Copilot AI Aug 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The getRemoteEntry function constructs URLs without proper validation, which could lead to URL injection vulnerabilities. Consider validating the port parameter and sanitizing the baseUrl to ensure it's a valid origin.

Suggested change
return `${baseUrl}:${port}/remoteEntry.js`;
// Validate port: must be integer between 1 and 65535
const portNum = Number(port);
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
throw new Error(`Invalid port: ${port}`);
}
// Validate baseUrl: must be a valid origin (scheme + host, no path/query/fragment)
let origin;
try {
const url = new URL(baseUrl);
// Only allow if baseUrl is origin (no path/query/fragment)
if (url.pathname !== '/' || url.search || url.hash) {
throw new Error();
}
origin = url.origin;
} catch {
throw new Error(`Invalid baseUrl: ${baseUrl}`);
}
return `${origin}:${portNum}/remoteEntry.js`;

Copilot uses AI. Check for mistakes.

};

init({
name: 'app1',
remotes: [
{
name: 'app2',
entry: 'http://localhost:3002/remoteEntry.js',
entry: getRemoteEntry(3002),
},
{
name: 'app3',
entry: 'http://localhost:3003/remoteEntry.js',
entry: getRemoteEntry(3003),
},
],
});

function useDynamicImport({ module, scope }) {
const [component, setComponent] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

useEffect(() => {
if (!module || !scope) return;
if (!module || !scope) {
setComponent(null);
setError(null);
return;
}

const loadComponent = async () => {
setLoading(true);
setError(null);
setComponent(null);

try {
console.log(`Loading remote module: ${scope}/${module}`);
const { default: Component } = await loadRemote(`${scope}/${module}`);
setComponent(() => Component);
console.log(`Successfully loaded: ${scope}/${module}`);
Copy link
Preview

Copilot AI Aug 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Console.log statements should be removed or replaced with a proper logging solution in production code. Consider using a conditional logger or removing debug statements for production builds.

Suggested change
console.log(`Successfully loaded: ${scope}/${module}`);
if (process.env.NODE_ENV !== 'production') {
console.log(`Loading remote module: ${scope}/${module}`);
}
const { default: Component } = await loadRemote(`${scope}/${module}`);
if (process.env.NODE_ENV !== 'production') {
console.log(`Successfully loaded: ${scope}/${module}`);
}

Copilot uses AI. Check for mistakes.

} catch (error) {
console.error(`Error loading remote module ${scope}/${module}:`, error);
setError(error);
} finally {
setLoading(false);
}
};

loadComponent();
}, [module, scope]);

return component;
return { component, loading, error };
}

function App() {
Expand All @@ -53,7 +129,54 @@ function App() {
});
};

const Component = useDynamicImport({ module, scope });
const { component: Component, loading, error } = useDynamicImport({ module, scope });

const renderRemoteComponent = () => {
if (loading) {
return (
<div style={{
padding: '2em',
textAlign: 'center',
backgroundColor: '#f8f9fa',
borderRadius: '4px',
border: '2px dashed #dee2e6'
}}>
<div>🔄 Loading {scope}/{module}...</div>
</div>
);
}

if (error) {
return (
<div style={{
padding: '2em',
border: '2px solid #ffc107',
borderRadius: '4px',
backgroundColor: '#fff3cd',
color: '#856404'
}}>
<h3>⚠️ Failed to Load Remote Component</h3>
<p>Could not load {scope}/{module}</p>
<details>
<summary>Error Details</summary>
<pre style={{ fontSize: '12px', overflow: 'auto', marginTop: '1em' }}>
{error.toString()}
</pre>
</details>
</div>
);
}

if (Component) {
return (
<ErrorBoundary>
<Component />
</ErrorBoundary>
);
}

return null;
};

return (
<div
Expand All @@ -68,10 +191,45 @@ function App() {
The Dynamic System will take advantage of Module Federation <strong>remotes</strong> and{' '}
<strong>exposes</strong>. It will not load components that have already been loaded.
</p>
<button onClick={setApp2}>Load App 2 Widget</button>
<button onClick={setApp3}>Load App 3 Widget</button>
<div style={{ marginBottom: '1em' }}>
<button
onClick={setApp2}
disabled={loading}
style={{
marginRight: '1em',
padding: '0.5em 1em',
backgroundColor: loading ? '#ccc' : '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: loading ? 'not-allowed' : 'pointer'
}}
>
Load App 2 Widget
</button>
<button
onClick={setApp3}
disabled={loading}
style={{
padding: '0.5em 1em',
backgroundColor: loading ? '#ccc' : '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: loading ? 'not-allowed' : 'pointer'
}}
>
Load App 3 Widget
</button>
</div>
<div style={{ marginTop: '2em' }}>
<Suspense fallback="Loading System">{Component ? <Component /> : null}</Suspense>
<Suspense fallback={
<div style={{ padding: '2em', textAlign: 'center' }}>
🔄 Initializing component...
</div>
}>
{renderRemoteComponent()}
</Suspense>
</div>
</div>
);
Expand Down
17 changes: 12 additions & 5 deletions advanced-api/dynamic-remotes/app1/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,20 @@ module.exports = {
// so it will always use the higher version found
shared: {
react: {
import: 'react', // the "react" package will be used a provided and fallback module
shareKey: 'react', // under this name the shared module will be placed in the share scope
shareScope: 'default', // share scope with this name will be used
singleton: true, // only a single version of the shared module is allowed
import: 'react',
shareKey: 'react',
shareScope: 'default',
singleton: true,
requiredVersion: '^18.3.1',
strictVersion: true,
},
'react-dom': {
singleton: true, // only a single version of the shared module is allowed
singleton: true,
requiredVersion: '^18.3.1',
strictVersion: true,
},
'react/jsx-runtime': {
singleton: true,
},
},
}),
Expand Down
4 changes: 2 additions & 2 deletions advanced-api/dynamic-remotes/app2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
},
"dependencies": {
"moment": "^2.29.4",
"react": "^16.13.0",
"react-dom": "^16.13.0"
"react": "^18.3.1",
"react-dom": "^18.3.1"
}
}
28 changes: 19 additions & 9 deletions advanced-api/dynamic-remotes/app2/rspack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,18 +58,28 @@ module.exports = {
'./Widget': './src/Widget',
},
shared: {
moment: deps.moment,
'react/jsx-dev-runtime': {},
moment: {
requiredVersion: deps.moment,
singleton: false,
},
'react/jsx-runtime': {
singleton: true,
},
'react/jsx-dev-runtime': {
singleton: true,
},
react: {
requiredVersion: deps.react,
import: 'react', // the "react" package will be used a provided and fallback module
shareKey: 'react', // under this name the shared module will be placed in the share scope
shareScope: 'default', // share scope with this name will be used
singleton: true, // only a single version of the shared module is allowed
requiredVersion: '^18.3.1',
import: 'react',
shareKey: 'react',
shareScope: 'default',
singleton: true,
strictVersion: true,
},
'react-dom': {
requiredVersion: deps['react-dom'],
singleton: true, // only a single version of the shared module is allowed
requiredVersion: '^18.3.1',
singleton: true,
strictVersion: true,
},
},
}),
Expand Down
24 changes: 16 additions & 8 deletions advanced-api/dynamic-remotes/app2/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,25 @@ module.exports = {
'./Widget': './src/Widget',
},
shared: {
moment: deps.moment,
moment: {
requiredVersion: deps.moment,
singleton: false,
},
react: {
requiredVersion: deps.react,
import: 'react', // the "react" package will be used a provided and fallback module
shareKey: 'react', // under this name the shared module will be placed in the share scope
shareScope: 'default', // share scope with this name will be used
singleton: true, // only a single version of the shared module is allowed
requiredVersion: '^18.3.1',
import: 'react',
shareKey: 'react',
shareScope: 'default',
singleton: true,
strictVersion: true,
},
'react-dom': {
requiredVersion: deps['react-dom'],
singleton: true, // only a single version of the shared module is allowed
requiredVersion: '^18.3.1',
singleton: true,
strictVersion: true,
},
'react/jsx-runtime': {
singleton: true,
},
},
}),
Expand Down
8 changes: 4 additions & 4 deletions advanced-api/dynamic-remotes/app3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
},
"dependencies": {
"moment": "^2.29.4",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-redux": "^7.2.0",
"redux": "^4.2.1"
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.1.2",
"redux": "^5.0.1"
}
}
Loading
Loading