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(),
},
};
}
@Hydrock
Copy link

Hydrock commented Oct 30, 2022

I think, i found answer in this article - https://dev.to/omher/lets-dynamic-remote-modules-with-webpack-module-federation-2b9m
At the same time, there is no re-rendering with nested loading of modular components.

@oravecz
Copy link

oravecz commented Apr 27, 2023

@shirly-chen-awx Did you ever find a solution to the __webpack_require__.l is not a function? We are experiencing the same strange behavior.

@ScriptedAlchemy
Copy link
Author

ensure the file is getting bundled by webpack and not treated as external. @oravecz

that error happens when something is importing it outside webpacks scope

@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