Learn how to set up webpack or Next.js to generate a CSS file from custom Material styles and automatically inject it into the header

One of the things I've done is define some custom material styles, like this:

import {createStyles, makeStyles, Theme} from '@material-ui/core/styles';

export const useStyles = makeStyles((theme: Theme) =>
    createStyles({

        fab: {
            zIndex:101,
            position: 'fixed',
            bottom: theme.spacing(2),
            right: theme.spacing(2),
        },

    }),
);

and also in this _document.tsx:

import React from 'react';
import { ServerStyleSheets } from '@material-ui/core/styles';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import IndexFab from '../src/components/common/fab';
import Loader from "../src/components/loader";

export default class MyDocument extends Document {
    render() {
        return (
            <Html lang="fa" dir={"rtl"}>
                <Head><title>a</title></Head>
                <body>
                <Main/>
                <NextScript />
                </body>
            </Html>
        );
    }
}


MyDocument.getInitialProps = async (ctx) =>
{

    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
        originalRenderPage({
            enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
        });

    const initialProps = await Document.getInitialProps(ctx);

    console.log( sheets.toString());
    return {
        ...initialProps,
        styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
    };
};

When I run the yarn build command (which runs next build within it), the css is rendered as styles text in the head section, for example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .fab {
            z-index: 101;
            position: 'fixed';
            bottom: 16px;
            right: 16px;
        }
    </style>
</head>
<body>
</body>
</html>

Now, my question is how do I configure webpack or nextjs to transform these styles into separate css files and then include them with appropriate link tags in the head section.

I'm still learning about webpack and nextjs ;).

Answer №1

A tactic we have been experimenting with involves storing the CSS in a separate file that is referenced in the head section:

const initialProps = await Document.getInitialProps(ctx)

// Generate and save stylesheet to public folder
const css = sheets.toString()
const cssPath = path.join(process.cwd(), 'public/styles')
fs.mkdirSync(cssPath, { recursive: true })
fs.writeFileSync(path.join(cssPath, 'muistyles.css'), css)

return {
  ...initialProps,
  styles: [...Children.toArray(initialProps.styles)]
}

We then linked this stylesheet in the <Head> of the _document. While this approach worked locally, when attempting to compile remotely on a Linux system, the generated CSS file was found to be empty. We will provide an update if a solution is discovered.

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

The next/font feature functions perfectly in all areas except for a single specific component

New Experience with Next.js and Tailwind CSS Exploring the next/font Package Delving into the realm of the new next/font package has been quite interesting. Following the tutorial provided by Next.js made the setup process smooth sailing. I've incorp ...

Creating dynamic pagination in an ant design table can be achieved by following these steps:

I am working with an Ant Design Table component and need to set up pagination based on the total count of users received from a server request. How can I customize the pagination in the Ant Design table to dynamically adjust based on the total count numb ...

AngularJS: Utilizing UI Bootstrap Popover with the Placement Set to 'bottom-right'

I am working with UI Bootstrap and AngularJS, attempting to customize a popover to have the 'bottom-right' placement instead of the default 'bottom' or 'right'. The desired functionality is illustrated in the image below. htt ...

Raising css properties using jquery

Is there a way to adjust CSS values using jQuery? I am looking to specifically increase values like top and left, but my current attempt is not producing the desired outcome: var left = 5; $(.object).css("left" + 5); The challenge I am facing is that I ...

What is causing the Unhandled Rejection (TypeError) error after I move the object in my Redux application and receive the message "Cannot read property 'filter' of undefined"?

I've been working on a Redux application. I've made modifications to a couple of files, and here are the changes in the two files: index.js: const store = createStore( reducer, { propReducer: { day: 1, data: [], filte ...

Tips for Creating an Animated Progress Bar in a Slider

After implementing jQuery, I managed to create a unique slider on my website. This slider included a thumbnail with captions for each photo. Positioned below the thumbnail was a progress bar fixed in the center between the caption and the image. Users can ...

What are the consequences of excluding a callback in ReactJs that may lead to dysfunctionality?

<button onClick = { () => this.restart()}>Restart</button> While going through a ReactJs tutorial, I encountered a game page which featured a restart button with the code snippet mentioned above. However, when I tried to replace it with the ...

Managing state changes in React can be a complex task, but

As a newcomer to React, I am currently working on creating an icon menu. However, I am facing an issue with my handleChange function not functioning as expected. While the icon Menu and possibleValues menu are visible, I am unable to select any of the op ...

Transmitting an array of data from React to Express/Node in order to conduct a

Struggling to transmit an array of ID numbers from React state, through Node/Express, and ultimately into MongoDB. The primary obstacle lies in figuring out how to send the array from React to the server. Once it's in a usable array format on the ser ...

Adjust the parent container to match the height of the child container when it is being hovered

I have been searching for a solution to this issue, but none of the answers I found seem to work in my specific case. Currently, I have a "Mega Menu" with links on the left side that expand when hovered over, revealing hidden links with images on the righ ...

Issue with fortawesome icon: relative and absolute positioning not functioning as expected

I have utilized a diamond symbol from the Fort Awesome icon collection and noticed that when I target the i tag in my CSS, the icon becomes highlighted (see screenshot attached). However, I am encountering issues with relative and absolute positioning not ...

I'm struggling to figure out how to specify the data type for storing an array of objects in a variable using React.useState

I am currently working on extracting values from an .xlsx file using the SheetJS library. Below, I will provide the code snippets, errors encountered, and the different approaches I have attempted. Data extracted from var dataToJson: (6) [{…}, {…}, { ...

Menu collapse button failing to Show content

My navigation menu button is not functioning correctly. I am currently working on this project using CodePen, so Bootstrap is already integrated into the code. <div class="navbar-header"> <button type="button" class="btn navbar-toggl ...

How can I make a popup modal in React without relying on external libraries?

I attempted to implement the method provided below, but unfortunately the modal is not effectively blurring out the rest of the content. I am looking for a way to ensure reusability without having to manipulate the elements' z-index properties. retur ...

Exploring the integration of react-admin and Material-UI version 5 for an enhanced user

Looking for guidance on integrating react-admin with Material UI version 5. Is there a way to decouple it from material ui 4? ...

My custom Material-UI theme created using createMuiTheme() doesn't seem to be functioning properly

When it comes to implementing the custom theme, I have followed the guidelines provided in the official docs. The code snippet is outlined below, however, there seems to be an issue where the text ('Some Text Here') is displaying in an incorrect ...

Center text vertically even when its number of lines is unknown

Can anyone help me figure out how to vertically center text that can be one or two lines long? The text also has a specific line-height set. I attempted the solution provided in this link but it didn't produce the desired result: <div> < ...

Having difficulty making Skrollr compatible with BootStrap 3 single page wonder

I am completely new to JavaScript, which is why I decided to use Skrollr. However, I have been facing some challenges in getting Skrollr to work properly on my webpage. I added the following code at the end of my page: <script type="text/javascript" sr ...

What is the best way to prevent excessive rerenders when verifying if database information has been successfully retrieved?

Hey there, I'm encountering an issue where the if statement check in my code is causing a "too many rerenders" problem. I'm trying to create a delay between pulling data from the database and calculating the BMI. Any suggestions on how to resolve ...

Utilizing CSS attr() for setting the width dimension

I'm having some trouble setting the width of an element using attr() in CSS. Chrome keeps giving me an "invalid property value" error and I can't figure out what's causing it. What I'm attempting to do is use the attribute "prog" as th ...