|
| 1 | +const path = require('path'); |
| 2 | +const HtmlWebpackPlugin = require('html-webpack-plugin'); |
| 3 | +const { container } = require('webpack'); |
| 4 | + |
| 5 | +module.exports = { |
| 6 | + mode: 'development', |
| 7 | + entry: path.resolve(__dirname, 'src/index.js'), |
| 8 | + output: { |
| 9 | + path: path.resolve(__dirname, 'build'), |
| 10 | + filename: 'host-bundle-[name].js', |
| 11 | + chunkFilename: 'host-chunk-[name].js', |
| 12 | + }, |
| 13 | + plugins: [ |
| 14 | + new container.ModuleFederationPlugin({ |
| 15 | + remotes: { |
| 16 | + myModule: `promise new Promise(resolve => { |
| 17 | + // This part depends on how you plan on hosting and versioning your federated modules |
| 18 | + if (globalThis.SharedWorkerGlobalScope) { |
| 19 | + const remoteUrlWithVersion = 'http://localhost:3001/worker/remoteEntry.js' |
| 20 | + importScripts(remoteUrlWithVersion) |
| 21 | + resolve(globalThis.myModule); |
| 22 | + return; |
| 23 | + } |
| 24 | + const remoteUrlWithVersion = 'http://localhost:3001/remoteEntry.js' |
| 25 | + const script = document.createElement('script') |
| 26 | + script.src = remoteUrlWithVersion |
| 27 | + script.onload = () => { |
| 28 | + // the injected script has loaded and is available on window |
| 29 | + // we can now resolve this Promise |
| 30 | + const proxy = { |
| 31 | + get: (request) => window.myModule.get(request), |
| 32 | + init: (...arg) => { |
| 33 | + try { |
| 34 | + return window.myModule.init(...arg) |
| 35 | + } catch(e) { |
| 36 | + console.log('remote container already initialized') |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + resolve(proxy) |
| 41 | + } |
| 42 | + // inject this script with the src set to the versioned remoteEntry.js |
| 43 | + document.head.appendChild(script); |
| 44 | + }) |
| 45 | + `, |
| 46 | + }, |
| 47 | + }), |
| 48 | + new HtmlWebpackPlugin({ |
| 49 | + template: path.resolve(__dirname, 'index.html'), |
| 50 | + }), |
| 51 | + ], |
| 52 | + devServer: { |
| 53 | + static: { |
| 54 | + directory: path.join(__dirname, 'build'), |
| 55 | + }, |
| 56 | + compress: true, |
| 57 | + port: 3000, |
| 58 | + } |
| 59 | +}; |
0 commit comments