Solving the style upload issue with NextJS and Module Federation in ReactJS

My current project utilizes React 18 and webpack 5 with the module federation plugin. I am exploring the possibility of integrating Next JS with module federation, but I am encountering an issue where the host project is not able to fetch styles from the remote project properly. This inconsistency in styling is causing a visually unappealing result, with some styles loading correctly while others fail to upload.

In my setup:

  • baseguicomponent -> host project
  • droninfocomponent -> remote project

The main problem lies in the rendering of styles across the projects.

Below is the configuration provided in my next.config.js file for the host project:

[...]

This piece of code showcases how the modules are configured within the project, along with the shared dependencies between them.

For the host index.js file:

[...]

And the corresponding package.json for the host project:

[...]

Similarly, for the remote project, here is the next.config.js configuration:

[...]

With this setup, the remote index.js file looks like this:

[...]

Followed by the package.json for the remote project:

[...]

However, despite setting up the configurations as illustrated above, I am facing difficulties sharing the _app.js file for the remote project. The loss of proper styling integration on the host project is puzzling because the standalone remote module appears unaffected. I have struggled to find adequate examples or resources related to module federation implementations in Next JS, leading to difficulty in resolving the styling discrepancies.

Answer №1

Utilize MiniCssExtractPlugin: Instead of using style-loader to extract styles into separate CSS files, consider using MiniCssExtractPlugin. This plugin allows you to convert styles into one or multiple distinct CSS files.

In both local next.config.js and host next.config.js:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    // ...
    webpack(config) {
        config.module.rules.push({
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                'css-loader',
            ],
        });

        config.plugins.push(
            new MiniCssExtractPlugin({
                filename: '[name].css',
            })
        );

        // ...
    },
};

Use css-loader with modules: To avoid class name conflicts, enable the modules parameter of the css-loader by setting it to true. This will automatically transform class names to unique identifiers.

module.exports = {
    // ...
    webpack(config) {
        config.module.rules.push({
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                {
                    loader: 'css-loader',
                    options: {
                        modules: true,
                    },
                },
            ],
        });

        // ...
    },
};

Try @loadable/component: For dynamically loading components and styles, give @loadable/component a try. This library offers more precise control over which styles and components are loaded in each module.

Install @loadable/component:

npm install @loadable/component

In your code:

import loadable from '@loadable/component';

const DronInfoApp = loadable(() => import('droninfocomponent/DronInfoApp'));

// ...

return (
    <div>
        <Head>
            {/* ... */}
        </Head>
        <main>
            <Suspense fallback={null}>
                <DronInfoApp />
            </Suspense>
        </main>
    </div>
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Error message "TypeError: element.type is undefined" indicates that the element is not recognized as a Mui

I'm currently working on constructing a form in React with material-ui, but encountering an issue when trying to import elements from material-ui. Here is the error message: see error here Beneath is a snippet of my code: import React from 're ...

The error message "Unexpected token < in JSON at position 0" is indicating a SyntaxError in the

I am facing an issue with the API on this specific page. Although the API is working fine on other pages, it seems to be encountering a problem here. I'm not sure what's causing the issue. Below is the code snippet: export async function getStati ...

Make updates to _app.tsx or _app.jsx in Next.js but the changes are not reflecting on the live site. This issue may be related to the

Here is how my pages/_app.tsx is structured: import type { AppProps } from "next/app"; import Head from "next/head"; import { MantineProvider } from "@mantine/core"; export default function App({ Component, pageProps }: AppP ...

Lock GridView headers when only scrolling vertically

I am facing an issue with my gridview on an aspx page. The gridview is wider than the page itself, so I want the headers of the gridview to scroll horizontally along with the content, while remaining fixed vertically. Can anyone help me achieve this? I hav ...

react-responsive: The children of a Responsive component do not have the capability to receive props

Utilizing the typical scenario described in the README file: const Desktop = props => ( <Responsive {...props} minWidth={1680} maxWidth={2560} /> ) const LaptopL = props => ( <Responsive {...props} minWidth={1440} maxWidth={1679} /> ...

What is the best way to align a div right below an image that has been clicked on?

I am designing a website that features social media icons spread out horizontally across the page. When a user clicks on one of these icons, I envision a pop-up window appearing below it, displaying additional information. Here is a visual representation o ...

Styling HTML Text Using Your Own Unique CSS Class Style

After developing some CSS classes to define specific hex colors for my web application, I ran into issues applying these styles to text in the HTML. Despite my best efforts, I am struggling to make the styles show up as intended. CSS .custom-orange-color ...

Error: The function sort cannot be applied to the result of calling the calendar method on the moment object

I retrieve the data from this URL. I am looking to display the data sorted by a recent date. I attempted to use the map method to render the data and then proceeded to sort it based on the date, but encountered an error. To organize the dates, I made use ...

Is it possible to utilize webpack for bundling a custom server in Next.js?

When developing a custom server with Next.js, it is important to note that it is not included in the production build. I am wondering if a custom webpack configuration can be used to bundle it instead? The reason behind my interest in this approach is to ...

With Next.js14, an error occurs when building with Nodejs20. The application runs smoothly on localhost, but encounters errors during the deployment process, resulting in a 500 internal server error

I recently updated my Node.js version to the latest, which is version 20. After that, I created a new project using Next.js. While it runs fine on my localhost, I encountered errors during the build process even though I didn't change any code. I&apos ...

What is the best way to modify the color of a button within an AngularJS function by utilizing the same button?

Currently, I have a function assigned to the ng-click event on a button in order to filter a list. My goal is to change the color of the button once it has been clicked and the filtered list is displayed. I am looking for a way to achieve this within the ...

Align the image and caption at the center in Bootstrap 4

I am presenting a figure that includes an image along with a caption. Here is the code for reference: <figure class="figure"> <img src="../img/atmpressure.svg" class="figure-img img-fluid" alt="pressue plot"> <figcaption class="figure-c ...

Waiting for the initial render before using document.getElementById() in next.js

I followed a tutorial that demonstrates how to access a canvas element by id using plain JavaScript. The tutorial can be found here. In the video, the method is explained around 5:10 and I adapted it for next.js in the code snippet below. import React, { u ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Solving the error message "window is not defined" in Nextjs

Hey, I'm attempting to create a component similar to [this tutorial][1] in my NextJS app but I'm running into an error ReferenceError: window is not defined //Navbar.js import styles from "../styles/Navbar.module.css"; export default fu ...

The width of the Div element is not following the specified dimensions, and it also has an unspecified margin

Check out my code snippet at: http://jsfiddle.net/8z4aw/ I'm trying to create a table-like layout using div elements, but for some reason the browser is not respecting the specified widths and seems to be adding an unwanted right margin. Where is thi ...

Retrieve all references to child elements in React

I am working on a component that renders dynamic children, and I need to assign a unique ref to each child (e.g. ref={'childID' + index}) After the children have been loaded, I am looking for a way to loop through them and access their refs. Is ...

Creating a loader for a specific component in Angular based on the view

Creating a loader for each component view is crucial when loading data from an API. Here is the current structure of my components within my <app-main></app-main>: <app-banner></app-banner> <app-data></app-data> <app ...

Maintain the aspect ratio of a div with CSS styling

Attempting to create a div while maintaining a 16:9 aspect ratio using CSS led me to conduct a Google search. Fortunately, I stumbled upon a helpful resource on Stack Overflow that detailed how to achieve this: How to maintain the aspect ratio. Excited to ...

When the dropdown form options in HTML are clicked, they appear disproportionately large compared to the initial select box

Sorry if my wording is a bit off, I'm still relatively new to working with CSS and HTML. I've encountered an issue where the dropdown options appear much larger than the select box itself when clicked. I can't seem to figure out how to fix i ...