Issues with @material-ui/core and react-bootstrap imports are causing disruptions to the NextJS build process

After researching, I've come to realize that this issue is common among developers. Unfortunately, none of the solutions I found have worked for me.

During npm run dev mode, everything in the project functions as expected, with all imports working seamlessly.

import { Typography } from "@material-ui/core";
import Card from 'react-bootstrap/Card'

For example, in a page, the imports work smoothly; however, as soon as I run npm build and visit the page, the imports seem to fail, resulting in no CSS applied.

Below is the content of my next.config.js file:

const withCSS = require('@zeit/next-css')

module.exports = withCSS({
  cssLoaderOptions: {
    url: false
  }
})

I have attempted to include MaterialUI and React-Bootstrap, but my efforts have been unsuccessful.

Any assistance in resolving this issue would be greatly appreciated. I'm puzzled as to why the build is failing.

Here is the content of my package.json file:

{
  "name": "name",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "prod": "next export"
  },
  "dependencies": {
    "@material-ui/core": "^4.8.2",
    "@material-ui/icons": "^4.5.1",
    "@zeit/next-css": "^1.0.1",
    "bootstrap": "^4.4.1",
    "next": "9.1.6",
    "next-compose-plugins": "^2.2.0",
    "nextjs-sitemap-generator": "^0.4.2",
    "react": "16.12.0",
    "react-bootstrap": "^1.0.0-beta.16",
    "react-dom": "16.12.0",
    "styled-components": "^4.4.1"
  }
}

Answer №1

Encountering issues with material-ui post version 4.3? The solution lies in preloading the CSS using _document.js.

The detailed explanation can be found in this link. To keep it concise, here is the code snippet to be added in _document.js for a visually appealing CSS.

import React from 'react'
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { ServerStyleSheets } from '@material-ui/styles'
import { createMuiTheme, responsiveFontSizes } from '@material-ui/core/styles'

const theme = responsiveFontSizes(createMuiTheme())

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <meta charSet="utf-8" />
          <meta
            name="viewport"
            content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
          />
          <meta name="theme-color" content={theme.palette.primary.main} />
          <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons"
          />
          <style jsx global>
            {`
              html,
              body {
                height: 100%;
                width: 100%;
              }
              *,
              *:after,
              *:before {
                box-sizing: border-box;
              }
              body {
                font-family: 'Roboto', 'Helvetica', 'Arial', sans-serif;
                font-size: 1rem;
                margin: 0;
              }
            `}
          </style>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

MyDocument.getInitialProps = async ctx => {
  // Render app and page and get the context of the page with collected side effects.
  const sheets = new ServerStyleSheets()
  const originalRenderPage = ctx.renderPage

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

  const initialProps = await Document.getInitialProps(ctx)

  return {
    ...initialProps,
    // Styles fragment is rendered after the app and page rendering finish.
    styles: [
      <React.Fragment key="styles">
        {initialProps.styles}
        {sheets.getStyleElement()}
      </React.Fragment>
    ]
  }
}

export default MyDocument


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

What steps can be taken to resolve the delay in transition when clicking on "read less

I implemented a transition effect for the Read More and Read Less buttons, however, there seems to be a delay on the transition when clicking on the Read Less button. This delay was not intentionally set by me. How can I resolve this issue and also apply a ...

Is it possible to incorporate an expression within NG-MODEL?

Is there a way to bind an expression inside the NG-MODEL directive without causing an error? Can this be achieved using a compile function? Below is my HTML markup: <!DOCTYPE html> <html> <head> <title></title> <l ...

Tips for achieving a full div image on hover

I'm having trouble with my CSS code for an image hover effect in a div. The image is appearing larger than the div and leaking out of it. How can I make sure the image stays contained within the div? Here's the updated CSS code: img { display ...

Is there a way for me to include .js or .cpp prior to using the Vim shortcut key gf?

When using a programming language like nodejs, the require function does not require the addition of the .js extension. For example: var Assert = require('./app_base'); However, in vim, when using gf, it cannot find app_base without the .js ext ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

Exploring the Differences Between API Routes and getStaticProps

Forgive my confusion, but I'm struggling to grasp the distinction between the two. So, with getStaticProps, you can fetch data and display it on the site. But isn't that the same as using API routes? In both cases, you're fetching data from ...

Enhancing Your Website with WordPress Customizer API: Introducing Kirki's Repeater Image Feature

Allow me to clarify this situation as thoroughly as I can. To begin with, I am utilizing a toolkit known as Kirki to enhance the WordPress Customizer API Within my theme, there is a section that features a 4-column layout of services, each accompanied by ...

The conditional statement within the EventListener does not seem to be functioning as intended

I am attempting to calculate BMI and then display additional information on the calculation result when a button is clicked. The 'what does this mean' button should show information based on the calculated BMI score. const generatebutton = doc ...

What is the best way to redirect a URL to include www using Node.js?

What is the best way to redirect a URL to start with www? For instance: ---> ...

How to build a login page with a static header and footer using Angular2

For my latest project, I am currently in the process of developing an application using Angular2 and eclipse Neon. Utilizing angular-cli for this app, I am now focused on creating the login page. Within the app.component.html file, you will find the follow ...

Setting up Firebase in Node.js with Express.js is a key step in developing

Setting up a Firebase instance (not firebase-admin) in Node.js. import { initializeApp } from 'firebase/app'; const firebaseConfig = { //... }; const app = initializeApp(firebaseConfig); This method may not be effective as Node.js uses Commo ...

What is the best way to organize images when adding them to the Strapi media library?

I am facing an issue with the order of images while uploading them using a drag and drop file input in my post car form. Currently, the images are being uploaded to strapi in the order of their size, from larger to smaller. Is there a way to upload them b ...

Utilizing jQuery in your webpack configuration for optimal performance

I encountered some issues while trying to test a simple project that involves using a jQuery function with webpack. The errors occurred during the bundling process and are as follows: ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot ...

Steps to transform an HTML form template into an HTML string

Below is an example of an object I am working with: $scope.item ={ fieldName:'First Name', fieldModel:'user.firstname', placeholder:'enter your name' } I intend to create an html form template as ...

The `stream.Transform.unshift()` method in Node.js

Let's take a look at this simple example: stream = require 'stream' util = require 'util' class TestTransform extends stream.Transform _transform: (chunk, encoding, callback) -> if not @noMore @noMore ...

Is there a way for me to obtain the theme palette from inside a component?

Currently, I am in the process of developing a component that will present an error message within a styled div. function ErrorDiv(props) { return ( <Card> <Typography>{props.message}</Typography> </Card> ); } My ...

Accessing variables in AngularJS from one function to another function

I am facing an issue where I need to access a variable in one function from another function. My code structure is as follows: NOTE: The value for submitData.alcohol is obtained from elsewhere in my code. angular.module('app',['ui.router&a ...

CSS: adjusting styles for different screen sizes on both desktop computers and smartphones

While diving into Emacs, I am in the process of creating a website called Prince. The layout of columns is controlled by the directives below: body { font-family: var(--s-font-family); font-size: var(--normal-font-size); column-count: 3; c ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

The operation failed because the property 'dasherize' is inaccessible on an undefined object

While attempting to execute the following command: ng generate component <component-name> An error occurred saying: Error: Cannot read property 'dasherize' of undefined Cannot read property 'dasherize' of undefined The confi ...