I'm a newbie to Next.js and module federation, and I'm working on an exercise (let's call it that) where I have a web component bundled with Webpack 5 in a federated module, and I want to import it into a Next.js project.
The issue is that I get a build error inside my Next.js: Module not found: Can't resolve 'navigationComponent/NavigationButtons'.
Is this doable in the first place? I read that there are some limitations with Next.js and module federation.
Will put below the config files: Web component webpack config (webpack.config.cjs):
const { container } = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = (_env, argv) => {
const isProduction = argv.mode === 'production';
return {
mode: argv.mode || 'development',
entry: './src/main.ts',
output: {
path: path.resolve(__dirname, 'dist'),
clean: true,
publicPath: isProduction ?
'https://abcexample.netlify.app/' :
'http://localhost:3001/'
},
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
plugins: [
new container.ModuleFederationPlugin({
name: 'navigationButtonsComponent',
filename: 'remoteEntry.js',
exposes: {
'./NavigationButtons': './src/components/navigation-buttons.ts',
},
}),
new HtmlWebpackPlugin({
template: './index.html',
}),
],
devServer: {
port: 3001,
open: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
}
}
};
Next.js (pages router) webpack config (next.config.ts):
import type { NextConfig } from "next";
import { NextFederationPlugin } from "@module-federation/nextjs-mf";
const nextConfig: NextConfig = {
reactStrictMode: true,
compiler: {
reactRemoveProperties: process.env.NODE_ENV === 'production',
},
webpack: (config, { isServer }) => {
if (isServer) return config;
config.plugins.push(
new NextFederationPlugin({
name: 'nextJsRandomApp',
remotes: {
navigationComponent: 'navigationButtonsComponent@http://localhost:3001/remoteEntry.js'
},
shared: {},
extraOptions: {},
})
);
return config;
}
};
export default nextConfig;
I tried different ways to import the module and the latest way is this:
useEffect(() => {
import('navigationComponent/NavigationButtons').catch(err => {
console.error('Failed to load navigation buttons component:', err);
});
}, []);
When I'm trying to load the remoteEntry.js file in the browser (http://localhost:3001/remoteEntry.js) it shows up correctly.
Thank you for your help and let me know if I can offer you more information