Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js Global CSS cannot be imported from files other than your Custom <App>

My React App was working fine, using global CSS also.

I ran npm i next-images, added an image, edited the next.config.js, ran npm run dev, and now I'm getting this message

Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.js.
Read more: https://err.sh/next.js/css-global

I've checked the docs, but I find the instructions a little confusing as I am new to React.

Also, why would this error happen now? Do you think it has anything to do with the npm install?

I've tried to remove new files I've added along with their code, but this doesn't fix the problem. I've also tried what the Read more: suggests.

My highest tier component.

import Navbar from './Navbar';
import Head from 'next/head';
import '../global-styles/main.scss';

const Layout = (props) => (
  <div>
    <Head>
      <title>Bitcoin Watcher</title>
    </Head>
    <Navbar />
    <div className="marginsContainer">
      {props.children}
    </div>
  </div>
);

export default Layout;

My next.config.js

// next.config.js
  const withSass = require('@zeit/next-sass')
  module.exports = withSass({
  cssModules: true
})

My main.scss file

@import './fonts.scss';
@import './variables.scss';
@import './global.scss';

my global.scss

body {
  margin: 0;
}
:global {
  .marginsContainer {
    width: 90%;
    margin: auto;
  }
}

The thing I find the weirdest is that this error came without changing anything to do with CSS, or Layout.js, and it was previously working?

I've moved my main.scss import to the pages/_app.js page, but the styles still aren't coming through. This is what the _app.js page looks like

import '../global-styles/main.scss'

export default function MyApp({ Component, props }) {
  return <Component {...props} />
}
like image 455
IndustryDesigns Avatar asked Mar 31 '20 01:03

IndustryDesigns


People also ask

How do I import a CSS file into Nextjs?

To add a stylesheet to your application, import the CSS file within pages/_app. js . Create a pages/_app. js file if not already present.

What is global in CSS?

What are global styles? When people talk about the global nature of CSS, they can mean one of a few different things. They may be referring to rules on the :root or <body> elements that are inherited globally (with just a few exceptions).

How do I style in next JS?

The easiest way to write CSS in a Next. js application is through its global stylesheet. Every newly created Next. js project comes with a styles folder and inside it, a global.


3 Answers

Use the built-in Next.js CSS loader (see here) instead of legacy @zeit/next-sass.

  1. Replace @zeit/next-sass package with sass.
  2. Remove next.config.js. Or do not change CSS loading in it.
  3. Move the global CSS as suggested in the error message.

Since Next.js 9.2 global CSS must be imported in Custom <App> component.

// pages/_app.js

import '../global-styles/main.scss'

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

To add styles only to a specific component or page you can use built-in support of CSS modules. (see here)

For example, if you have a component Button.js you can create a Sass file button.module.scss and include it in the component.

like image 118
Nikolai Kiselev Avatar answered Oct 21 '22 20:10

Nikolai Kiselev


Next.js stops complaining when your file has module in naming, e.g., changing import '../global-styles/main.scss'; to import '../global-styles/main.module.scss'; would fix the warning and you could have your styles in the global-styles, or for example, in your component.

No extra dependencies/configurations in next.config.js is required.

like image 23
Daniel Danielecki Avatar answered Oct 21 '22 21:10

Daniel Danielecki


You can replace the opinionated (and overly-complex?) NextJs CSS loaders with your own. Here's a simple one for global css:

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

module.exports = {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Find and remove NextJS css rules.
    const cssRulesIdx = config.module.rules.findIndex(r => r.oneOf)
    if (cssRulesIdx === -1) {
      throw new Error('Could not find NextJS CSS rule to overwrite.')
    }
    config.module.rules.splice(cssRulesIdx, 1)

    // Add a simpler rule for global css anywhere.
    config.plugins.push(
      new MiniCssExtractPlugin({
        experimentalUseImportModule: true,
        filename: 'static/css/[contenthash].css',
        chunkFilename: 'static/css/[contenthash].css',
      })
    )

    config.module.rules.push({
      test: /\.css$/i,
      use: !isServer ? ['style-loader', 'css-loader'] : [MiniCssExtractPlugin.loader, 'css-loader'],
    })
    return config
  },
}
like image 29
Dominic Avatar answered Oct 21 '22 22:10

Dominic