Skip to content

Instantly share code, notes, and snippets.

@jacob-ebey
Created February 24, 2021 00:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacob-ebey/a2ba70de4666f99b0aa756a4577f4383 to your computer and use it in GitHub Desktop.
Save jacob-ebey/a2ba70de4666f99b0aa756a4577f4383 to your computer and use it in GitHub Desktop.
Consume Federated Modules With Local Fallback | Unpkg, NPM
const path = require("path");
const { camelCase } = require("camel-case");
const webpack = require("webpack");
const { merge } = require("webpack-merge");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const pkg = require("./package.json");
function unpkgRemote(name) {
const version = pkg.dependencies[name];
return [
`${camelCase(
name
)}@https://unpkg.com/${name}@${version}/dist/browser/remote-entry.js`,
`${camelCase(name)}@/remote-fallbacks/${name}/remote-entry.js`,
];
}
function unpkgRemoteFallback(name) {
return {
from: path.dirname(require.resolve(`${name}/dist/browser/remote-entry.js`)),
to: `remote-fallbacks/${name}`,
};
}
/** @type {webpack.Configuration} */
const baseConfig = {
mode: process.env.NODE_ENV === "development" ? "development" : "production",
};
/** @type {webpack.Configuration} */
const browserConfig = {
output: {
path: path.resolve("./dist/browser"),
},
plugins: [
new HtmlWebpackPlugin(),
new CopyPlugin({
patterns: [unpkgRemoteFallback("versioned-federated-module")],
}),
new webpack.container.ModuleFederationPlugin({
remotes: {
"versioned-federated-module": unpkgRemote("versioned-federated-module"),
},
}),
],
};
/** @type {webpack.Configuration} */
const nodeConfig = {
target: "node",
output: {
path: path.resolve("./dist/node"),
},
plugins: [
new webpack.container.ModuleFederationPlugin({
remoteType: "commonjs",
remotes: {
"versioned-federated-module": "versioned-federated-module",
},
}),
],
};
module.exports = [
merge(baseConfig, browserConfig),
merge(baseConfig, nodeConfig),
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment