Skip to content

Instantly share code, notes, and snippets.

@ScriptedAlchemy
Last active February 14, 2024 02:25
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ScriptedAlchemy/3a24008ef60adc47fad1af7d3299a063 to your computer and use it in GitHub Desktop.
Save ScriptedAlchemy/3a24008ef60adc47fad1af7d3299a063 to your computer and use it in GitHub Desktop.
The Right Way to Load Dynamic Remotes
import { injectScript } from '@module-federation/utilities';
// example of dynamic remote import on server and client
const isServer = typeof window === 'undefined';
//could also use
// getModule({
// remoteContainer: {
// global: 'app2',
// url: 'http://localhost:3002/remoteEntry.js',
// },
// modulePath: './sample'
// }).then((sample) => {
// console.log(sample)
// });
const dynamicContainer = injectScript({
global: 'checkout',
url: `http://localhost:3002/_next/static/${
isServer ? 'ssr' : 'chunks'
}/remoteEntry.js`,
}).then((container) => {
return container.get('./CheckoutTitle').then((factory) => {
return factory();
});
});
// if you wanted to use it server side/client side in next.js
const DynamicComponent = React.lazy(() => dynamicContainer);
// eslint-disable-next-line react/display-name
export default (props) => {
return (
<>
<React.Suspense>
<DynamicComponent />
</React.Suspense>
<p>Code from GSSP:</p>
<pre>{props.code}</pre>
</>
);
};
export async function getServerSideProps() {
return {
props: {
code: (await dynamicContainer).default.toString(),
},
};
}
@oravecz
Copy link

oravecz commented Apr 28, 2023

Yes, it was a duplicate of module-federation/core#551

I'm surprised it isn't discussed more, especially on the @module-federation/utilities page. importRemote is the function that is calling __webpack_require__.l(), and I would expect any production build using that package would tree-shake away the function without that plugin.

Is this plugin available as an npm published webpack plugin at this time?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment