|
| 1 | +# Patternslib Module Federation |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +For a general introduction see: https://webpack.js.org/concepts/module-federation/ |
| 6 | + |
| 7 | +Module Federation allows to share dependencies between bundles. |
| 8 | +Each bundle includes the whole set of dependencies. |
| 9 | +However, if multiple bundles have the same dependencies they are only loaded once. |
| 10 | + |
| 11 | +For example, if bundle A and B both depend on jQuery and bundle A has already loaded it, bundle B can just reuse the already loaded jQuery file. |
| 12 | +But if only bundle B is loaded, it uses its own bundled version of the jQuery library. |
| 13 | + |
| 14 | +There is a host bundle - in the fictional example above our bundle "A". |
| 15 | +Other bundles are "remotes" which are initialized for module federation by the host bundle "A" |
| 16 | + |
| 17 | + |
| 18 | +## How to use it |
| 19 | + |
| 20 | +- Create a new entry point ``index.js`` which only imports the normal entry point. |
| 21 | + If your bundle is the host bundle, also import the ``module_federation`` module - importing is enough. |
| 22 | + |
| 23 | +``` |
| 24 | +import "@patternslib/patternslib/webpack/module_federation"; |
| 25 | +import("./patterns"); |
| 26 | +``` |
| 27 | + |
| 28 | +- Add the module federation plugin in webpack. There is a configuration factory which you can use for that like so: |
| 29 | + |
| 30 | +``` |
| 31 | +const package_json = require("./package.json"); |
| 32 | +const path = require("path"); |
| 33 | +const patternslib_config = require("@patternslib/patternslib/webpack/webpack.config"); |
| 34 | +const mf_config = require("@patternslib/patternslib/webpack/webpack.mf"); |
| 35 | +
|
| 36 | +module.exports = (env, argv) => { |
| 37 | + let config = { |
| 38 | + entry: { |
| 39 | + "bundle.min": path.resolve(__dirname, "src/index.js"), |
| 40 | + }, |
| 41 | + }; |
| 42 | +
|
| 43 | + config = patternslib_config(env, argv, config, ["mockup"]); |
| 44 | +
|
| 45 | + // ... |
| 46 | +
|
| 47 | + config.plugins.push( |
| 48 | + mf_config({ |
| 49 | + package_json: package_json, |
| 50 | + remote_entry: config.entry["bundle.min"], |
| 51 | + }) |
| 52 | + ); |
| 53 | +
|
| 54 | + return config; |
| 55 | +}; |
| 56 | +``` |
| 57 | + |
| 58 | +That's basically it. |
| 59 | + |
| 60 | +For more information look at the source code at ``@patternslib/webpack/module_federation`` and ``@patternslib/webpack/webpack.mf.js``. |
| 61 | + |
0 commit comments