Webpack 5 module federation error handling - reactjs

I've a micro frontends running on monorepo using nx CLI where in the host application I'm using module federation to get the remoteEntry.js files from all the micro frontends and serve them as components per route.
I've error boundary which works perfect on dev / staging / production environment and displays 404 page when the remoteEntry is not fetched / crashed for some reason and it works as expected.
But when I want to run unit tests on the shell application to test its functionality and I'm running only the shell application, for some reason I'm receiving errors from webpack saying the following:
Loading script failed.
(error: http://localhost:3107/remoteEntry.js)
Which is expected, because I didn't run any of the micro frontends.
What I want to achieve is that I will be able to run only the shell application locally and get the 404 page also on local without having this error, in other words - I want to handle the errors when the micro frontends are not live.
Any suggestions how can I achieve that?
webpack file on the shell application:
const nrwlConfig = require('#nrwl/react/plugins/webpack.js');
const { ModuleFederationPlugin } = require('webpack').container;
const deps = require('../../package.json').dependencies;
const { remoteEntries } = require('./remoteEntries');
const EnvType = {
LOCAL: 'local',
PLAYGROUND: 'playground',
DEVELOPMENT: 'development',
STAGING: 'staging',
PRODUCTION: 'production',
};
module.exports = (config) => {
nrwlConfig(config);
config.optimization.runtimeChunk = 'single';
return {
...config,
plugins: [
...config.plugins,
new ModuleFederationPlugin({
name: 'hostApp',
filename: 'remoteEntry.js',
remotes: {
app1: `app1#${getRemoteEntryUrl(remoteEntries.APP1)}`,
app2: `app2#${getRemoteEntryUrl(remoteEntries.APP2)}`,
app3: `app3#${getRemoteEntryUrl(
remoteEntries.APP3
)}`,
app4: `app4#${getRemoteEntryUrl(
remoteEntries.APP4
)}`,
app5: `app5#${getRemoteEntryUrl(remoteEntries.APP5)}`,
app6: `app6#${getRemoteEntryUrl(
remoteEntries.APP6
)}`,
app7: `app7#${getRemoteEntryUrl(
remoteEntries.APP7
)}`,
},
shared: {
...deps,
react: {
singleton: true,
eager: true,
requiredVersion: deps.react,
},
'react-dom': {
singleton: true,
eager: true,
requiredVersion: deps['react-dom'],
},
},
}),
],
};
};
const getRemoteEntryUrl = (entry) => {
const { NODE_ENV } = process.env || EnvType.DEVELOPMENT;
if (NODE_ENV !== EnvType.LOCAL) {
return entry.remoteEntries[NODE_ENV];
}
return `http://localhost:${entry.localPort}/remoteEntry.js`;
};

Related

MFE module federation cannot find module for remote child import

Im trying to build out a micro frontend for the first time so my main application can support a sub application. I have it all working when everything is just rendering App.tsx (remote) but as soon as I try and render a child within the remote application I get the Cannot find module error from webpack
Container craco.congig.js
/* eslint-disable #typescript-eslint/no-var-requires */
const CracoEsbuildPlugin = require('craco-esbuild');
const { ModuleFederationPlugin } = require("webpack").container;
const deps = require("./package.json").dependencies;
module.exports = {
webpack: {
plugins: {
add: [
new ModuleFederationPlugin({
name: "Dashboard",
remotes: {
DigitalCanopy: "DigitalCanopy#//localhost:3001/remoteEntry.js",
},
shared: {
react: {
singleton: true,
strictVersion: true,
requiredVersion: deps['react']
},
"react-dom": {
singleton: true,
strictVersion: true,
requiredVersion: deps['react-dom']
},
},
}),
],
},
...
My remote craco.config.js
/* eslint-disable #typescript-eslint/no-var-requires */
const CracoEsbuildPlugin = require('craco-esbuild');
const { ModuleFederationPlugin } = require("webpack").container;
const deps = require("./package.json").dependencies;
module.exports = {
devServer: {
port: 3001
},
webpack: {
plugins: {
add: [
new ModuleFederationPlugin({
name: "DigitalCanopy",
exposes: {
"./DigitalCanopy": "./src/App.tsx",
},
filename: "remoteEntry.js",
shared: {
react: { singleton: true },
"react-dom": { singleton: true },
},
}),
],
},
configure: (webpackConfig) => ({
...webpackConfig,
output: {
...webpackConfig.output,
publicPath: "auto",
},
}),
},
plugins: [
{
plugin: CracoEsbuildPlugin,
options: {
esbuildLoaderOptions: {
// Optional. Defaults to auto-detect loader.
loader: 'tsx', // Set the value to 'tsx' if you use typescript
target: 'es2018',
},
esbuildMinimizerOptions: {
target: 'es2018',
css: true, // if true, OptimizeCssAssetsWebpackPlugin will also be replaced by esbuild.
},
skipEsbuildJest: false, // Optional. Set to true if you want to use babel for jest tests,
esbuildJestOptions: {
loaders: {
'.ts': 'ts',
'.tsx': 'tsx',
},
},
},
},
],
};
My remote App.tsx
import { createTheme, ThemeProvider } from '#mui/material';
import React from 'react';
import './App.css';
import App1 from './App1';
const baseTheme = createTheme({
...MUI THEME STUFF
});
function App() {
return (
<ThemeProvider theme={baseTheme}>
<div className="App">Digital Canopy App</div>;
<App1 />
</ThemeProvider>
);
}
export default App;
This works and renders fine until I try and render <App1 />
Then I get this error Module not found: Error: Can't resolve './App1' in ...
Any ideas? I feel like this should just work. Importing children components from within the remote is pretty standard doesnt seem unique but I cannot find anything similar online which makes me think Im missing something obvious.
Thanks for the help
My issue was I was missing the .tsx extension on the import. I have no idea why that is required by the sub application. My build configs are identical for typescript and my main app does not require that. I'll dig in and try and figure out why

Webpack Module Federation loads chunks from wrong URL

I am building a project with webpack module federation with the following setup:
React host (running on localhost:3000)
Angular Remote 1 (running on localhost:4201)
Angular Remote 2 (running on localhost:4202)
The goal is to get both remotes working. If I only run one of the and remove the other it is working perfectly.
The issue I am facing is that when the remotes are loaded, __webpack_require__.p is set by one of the remotes' script and therefore the other remote's chunk is loaded from the wrong url.
Here is the error I get:
My module federation config is the following:
React host:
.
.
.
new ModuleFederationPlugin({
name: "react_host",
filename: "remoteEntry.js",
remotes: {
angular_remote_1: "angular_remote_1#http://localhost:4201/angular_remote_1.js",
angular_remote_2: "angular_remote_2#http://localhost:4202/angular_remote_2.js"
},
exposes: {},
shared: {
...deps,
react: {
singleton: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
requiredVersion: deps["react-dom"],
},
},
}),
.
.
.
Angular Remote 1
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
output: {
publicPath: "auto",
uniqueName: "angular_remote_1",
scriptType: "text/javascript"
},
optimization: {
runtimeChunk: false
},
experiments: {
outputModule: true
},
plugins: [
new ModuleFederationPlugin({
name: "angular_remote_1",
library: { type: "var", name: "angular_remote_1" },
filename: "angular_remote_1.js",
exposes: {
'./angularRemote1': './src/loadAngularRemote1.ts',
},
shared: ["#angular/core", "#angular/common", "#angular/router"]
})
],
};
Angular Remote 2
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
output: {
publicPath: "auto",
uniqueName: "angular_remote_2",
scriptType: "text/javascript"
},
optimization: {
runtimeChunk: false
},
experiments: {
outputModule: true,
},
plugins: [
new ModuleFederationPlugin({
name: "angular_remote_2",
library: { type: "var", name: "angular_remote_2" },
filename: "angular_remote_2.js",
exposes: {
'./angularRemote2': './src/loadAngularRemote2.ts',
},
shared: ["#angular/core", "#angular/common", "#angular/router"]
})
],
};
Thins I have tried so far:
Playing around with public path (between auto and hardcoded)
Setting a custom chunkLoadingGlobal for both remotes (not the host)
The exact reproduction of this issue can be found here: https://github.com/BarniPro/react-host-angular-remotes-microfrontend
Any help is greatly appreciated.
The issue can be solved by setting the topLevelAwait experiment to true in the remotes's webpack.config.js:
experiments: {
topLevelAwait: true,
},
This results in the two remotes loading in sync which prevents the paths from overriding each other.
Another update I had to make was disabling the splitChunks option in the remotes' optimization settings (see SplitChunksPlugin):
optimization: {
runtimeChunk: false, // This is also needed, but was added in the original question as well
splitChunks: false,
}
The Github repo has been updated with the working solution.

Cannot convert lodash library from CommonJS to ES in Vitejs

I am building a project using Vite + React + Antd.
My project has lodash library, when i build with vite build command then get an error like below:
Running on environment production
vite v2.9.9 building for production...
transforming (2741) node_modules\.pnpm\lodash#4.17.21\node_modules\lodash\isLength.jsUnexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:
(commonjs) load "\u0000cross-fetch?commonjs-proxy"
error during build:
Error: Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:
(commonjs) load "\u0000cross-fetch?commonjs-proxy"
In my vite.config.js file, I added #rollup/plugin-commonjs,
import commonjs from '#rollup/plugin-commonjs';
import react from '#vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
export default ({ mode }) => {
const env = loadEnv(mode, 'env');
const htmlPlugin = () => {
return {
name: 'html-transform',
// Replace %VITE_X% env variables in index.html.
transformIndexHtml(html: string) {
return html.replace(/%(.*?)%/g, function match(_match, p1) {
return env[p1];
});
},
};
};
return defineConfig({
resolve: {
alias: [
{ find: /^~/, replacement: '' },
{ find: 'react/jsx-runtime', replacement: 'react/jsx-runtime.js' },
],
},
define: {
'process.env': process.env,
},
build: {
outDir: './build',
rollupOptions: {
plugins: [commonjs()],
},
commonjsOptions: {
exclude: [/./],
},
},
publicDir: './public',
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
},
optimizeDeps: {
include: ['#ant-design/icons'],
},
plugins: [
htmlPlugin(),
react({
babel: {
plugins: [['#babel/plugin-transform-react-jsx', { runtime: 'automatic' }]],
},
}),
],
});
};
I tried to change lodash into lodash-es, but in my node_modules has a couple of libraries use it.
Please help me. Thank all

Webpack Module Federation fails with Next JS when using styled-components

I'm trying to get Webpack Module Federation working with a NextJS app where the federated module is using styled-components. My configuration is working as expected if I'm only using react and react-dom but using styled-components gives me these errors:
It looks like there are several instances of 'styled-components' initialized in this application. This may cause dynamic styles to not render properly, errors during the rehydration process, a missing theme prop, and makes your application bigger without good reason.
and
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
I have tried the different approaches to resolve styled-components to a single instance by modifying the Webpack config in both the host and remote apps, but all seem to fail.
Here is my current configuration:
Federated modules repo (webpack.config.js):
const { ModuleFederationPlugin } = require("webpack").container;
const deps = require("./package.json").dependencies;
const path = require("path");
module.exports = {
mode: "development",
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 3001,
},
output: {
publicPath: "auto",
},
resolve: {
extensions: [".js"],
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
exclude: /node_modules/,
options: {
plugins: [
["babel-plugin-styled-components", { pure: true, ssr: true }],
],
presets: ["#babel/preset-react"],
},
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "remoteLib",
filename: "remoteEntry.js",
exposes: {
"./Button": "./src/Button",
},
shared: {
...deps,
react: {
singleton: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
requiredVersion: deps["react-dom"],
},
"styled-components": {
singleton: true,
requiredVersion: deps["styled-components"],
},
},
}),
],
};
Consuming NextJS app Webpack config (next.config.js):
webpack: (config, options) => {
const { ModuleFederationPlugin } = options.webpack.container;
config.plugins.push(
new ModuleFederationPlugin({
remotes: {
'federated-components': 'remoteLib#http://localhost:3001/remoteEntry.js'
}
})
);
return config;
}

Gatsby build failing on Netlify. Warning: a promise was created in a handler

Build Errors on Netlify. Build exceeds maximum allowed runtime.
Can build locally running yarn build and inside the Netlify docker container, however when on Netlifys build it exceeds maximum allowed runtime.
Am getting some warnings like the below when running in the Netlify docker container
Warning: a promise was created in a handler at opt/buildhome/repo/node_modules/postcss/lib/lazy-result.js:213:17 but was not returned from it
Warning: a promise was created in a handler at /opt/buildhome/repo/node_modules/gatsby-transformer-remark/extend-node-type.js:179:19 but was not returned from it
Those two warnings are pointing to two Gatsby plugins I have configured. (Config below)
require('dotenv').config();
module.exports = {
siteMetadata: {
title: 'My Website',
},
proxy: {
prefix: '/.netlify/functions',
url: 'http://localhost:9000',
},
plugins: [
'gatsby-plugin-eslint',
'gatsby-plugin-react-helmet',
'gatsby-plugin-postcss',
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: process.env.SPACE_ID,
accessToken: process.env.ACCESS_TOKEN,
},
},
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
exclude: /img/,
},
},
},
'gatsby-plugin-sharp',
{
resolve: 'gatsby-transformer-remark',
options: {
plugins: [
{
resolve: 'gatsby-remark-images-contentful',
options: {
maxWidth: 590,
},
},
],
},
},
'gatsby-plugin-netlify', // make sure to keep it last in the array
],
};
Have tried to debug all weekend but not sure what else to do. I couldn't find anyone else who has had similar issues.

Resources