Module Federation, Js bundler tool for micro-frontend
Rauf Rahman
Building Scalable APIs for LLMs | Ex-SAP | MLOps Practitioner | Solution Architect
What are bundlers eg: Webpack, RsPack
A bundler is a packaging system to package code into a single file for distribution.
Bundler works as a compiler, A compiler compiles language into LLVM IR.
A bundler first creates a module graph, then tree shaking, code splitting, minifying, and finally generates JS code for distribution.
modern bundlers support plugins and various loaders for different stack variances.
There is a lot to tell about bundlers but our focus is different for now.
Module Federation
Module federation is a feature of Webpack and RsPack to load dynamic code. Enable efficient ways of code splitting, sharing, and dependency management. Get very popular with the Micro-Frontend pattern. Can split monolith application in micro-frontend.
Three main concepts include:
Simple used case, where AppA exposes a Link component and sets a shared React dependency, and AppB consumes the components and libraries provided by AppA:
// AppA config
new ModuleFederationPlugin({
name: 'AppA',
filename: 'remoteEntry.js',
exposes: {
'.': './src/Link.tsx',
},
shared: {
'react': {
version: '18.1.0'
}
}
})
// AppB config
new ModuleFederationPlugin({
library: { type: 'module' },
remotes: {
'AppA': 'component_app@https://localhost:3001/remoteEntry.js',
},
shared: ['react'],
})
After building it generates two things.
Also, it supports some awesome tools like Medusa.
After doing a small PoC I realized, that in micro frontend architecture, horizontal splitting will get more benefits from module federation than vertical splitting.
Some patterns will be beneficial like :
领英推荐
Another pattern that can be useful is the Component Label Ownership.
Monorepos are good for bootstraping an MVP but in the scaling question, it causes problems like, release train, singletone-issues.
Module federation helps to sort out this on build-time instead spiral into the runtime.
Only use singletone: true when there is a context involvement, like Reudx, theme provider. Just remember using singletone, will block multiple versions of a module.
Avoid eager: true, It creates compatibility issues with libraries.
Start Code/entry points
This code is shareable runtime code for remote container startup. This is very useful in Module Federation, because of the encapsulation of the runtimes. This is easy in webpack environment but with module federation, it's a difficult operation.
RsPack
Why mentioning? because with their latest update, the module bundler can be integrated or migrated to RsPack easily. Also created by same organization.
Launched in 2003, Js bundler to ease the WebPack drawbacks. Developed by ByteDance, the mother company of TikTok.
The total build time is the key point for this rust-based bundler. Showed very impressive results in benchmarking.
For more nice things about RsPack https://www.rspack.dev/guide/introduction.html#why-rspack