Last active
October 16, 2024 22:52
-
-
Save ScriptedAlchemy/3a24008ef60adc47fad1af7d3299a063 to your computer and use it in GitHub Desktop.
The Right Way to Load Dynamic Remotes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(), | |
}, | |
}; | |
} |
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
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