22
votes

I am creating a project with react, redux and next.js, and want to import CSS files in js.

I followed instructions in next.js/#css and next-css, but find out that CSS styles do not work.

My code is as follow:

pages/index.js:

import React from 'react'
import "../style.css"

class Index extends React.Component {
    render() {
        return (
            <div className="example">Hello World!</div>
        );
    }
}

export default Index

next.config.js:

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

style.css:

.example {
    font-size: 50px;
    color: blue;
}

package.json:

{
    "name": "my-app",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@zeit/next-css": "^0.1.5",
        "next": "^6.0.0",
        "react": "^16.3.2",
        "react-dom": "^16.3.2",
        "react-redux": "^5.0.7",
        "react-scripts": "1.1.4",
        "redux": "^4.0.0",
        "redux-devtools": "^3.4.1"
    },
    "scripts": {
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject",
        "dev": "next",
        "build": "next build",
        "start": "next start"
    }
}

Questions:

1. There is an "Uncaught SyntaxError" in Chrome, but it seems to not affect the rendering of the page. But I still wondering the reason and the solution. index.js error in chrome is below img

2. As shown in Chrome, there's no "example" class, which means the style.css file is not loaded. Am I missing anything? no CSS file in chrome

Thanks in advance.

9
Hi @ArgentBarbie, did you create the _document.js file in the pages directory? Can you paste the code in here too if you have?mtl
@mtl Sorry, I didn't create _document.js. Is it necessary? What should be inside the file?ArgenBarbie
Hi @ArgentBarbie, in the future, try to only ask one question at a time :). If you have two questions, simply ask two separate questions. It makes it easier to answer for two different people who might only have the answers to one of the questions. And it makes the individual questions searchable, helping other people with the same issue. Good luck with Next.js!mtl

9 Answers

22
votes

EDIT 2: As of Next.js > 10, you can import a global CSS file into _app.js, and you can use CSS modules in your components. More in the Next.js docs.


EDIT: As of Next.js 7, all you have to do to support importing .css files is to register the withCSS plugin in your next.config.js. Start by installing the plugin as dev dependency:

npm install --save-dev @zeit/next-css

Then create the next.config.js file in your project root and add the following to it:

// next.config.js
const withCSS = require('@zeit/next-css')
module.exports = withCSS({/* my next config */})

You can test that this is working by creating a simple page and importing some CSS. Start by creating a CSS file:

// ./index.css
div {
    color: tomato;
}

Then create the pages folder with an index.js file. Then you can do stuff like this in your components:

// ./pages/index.js
import "../index.css"
export default () => <div>Welcome to next.js 7!</div>

You can also use CSS modules with a few lines of config. For more on this check out the documentation on nextjs.org/docs/#css.


Deprecated: Next.js < 7:

You'll also need to create a _document.js file in your pages folder and link to the compiled CSS file. Try it out with the following content:

// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
      <html>
        <Head>
          <link rel="stylesheet" href="/_next/static/style.css" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

The stylesheet is compiled to .next/static/style.css which means that the CSS file is served from /_next/static/style.css, which is the value of the href attribute in the link tag in the code above.

As for the first question, it's probably Chrome not understanding the import syntax. Try to enable the Experimental Web Platform flag in chrome:flags and see if that solves it.

4
votes

For anyone who comes here ,the new Next JS supports CSS out of the box. The catch is that for modules (components), they must be named as the component. So, if you have a header inside a components directory, it must be named header.module.css

built-in-css-module-support-for-component-level-styles

2
votes

As Zeit said :

  1. Create a /static folder at the same level the /pages folder.
  2. In that folder put your .css files
  3. In your page components import Head and add a to your CSS.

import Head from 'next/head'

function IndexPage() {
  return (
    <div>
      <Head>
        <title>My page title</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
      </Head>
      <p>Hello world!</p>
    </div>
  )
}

export default IndexPage

And that's it, this way Next.js should render the link tag in the head of the page and the browser will download the CSS and apply it.

Thanks Sergiodxa at Github for this clear solution.

2
votes

Add {name}.css to src/static/styles/.

Then modify the Head in src/pages/_document.js to include the following link:

<Head>
    <link href="/static/styles/{name}.css" rel="stylesheet">
</Head>
1
votes

you need create to custom _document.js file.

Custom document when adding css will look like:

import React from "react";

import Document, { Head, Main, NextScript } from "next/document";

export default class MyDocument extends Document {

  render() {
    const { buildManifest } = this.props;
    const { css } = buildManifest;
    return (
      <html lang="fa" dir="rtl">
        <Head>
          {css.map(file => (
            <link rel="stylesheet" href={`/_next/${file}`} key={file} />
          ))}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}
1
votes

If you use next.js do this.

create next.config.js in root projects

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

function HACK_removeMinimizeOptionFromCssLoaders(config) {
    console.warn(
        'HACK: Removing `minimize` option from `css-loader` entries in Webpack config',
    );
    config.module.rules.forEach(rule => {
        if (Array.isArray(rule.use)) {
            rule.use.forEach(u => {
                if (u.loader === 'css-loader' && u.options) {
                    delete u.options.minimize;
                }
            });
        }
    });
}

module.exports = withCSS({
    webpack(config) {
        HACK_removeMinimizeOptionFromCssLoaders(config);
        return config;
    },
});

Don't forget to restart the server

0
votes

for next above 9.3, global css is written in "styles/globals.css" and you can import it to _app.js

    import "../styles/globals.css";

Then for each component, you can write its own css and import it into the component. Pay attention to the naming:nameOfFile.module.css

Let's say you have "product.js" component and "product.module.css". you want to load css from "product.css" into "product.js"

import classes from "./product.module.css" // assuming it's in the same directory

you put all class names into product.module.css. Assume you have .main-product in product.module.css. Inside product.js, let's say you have a div to style

<div className={classes.main-product}  > </div>

with the css module feature, you can use the same className in other components and it wont conflict. Because when next.js compiles, it will hash the name of the className, using its module. So hashed values of same classnames from different modules will be same

0
votes

Set this to false if your app works directly with the web 5 package.

module.exports = {
  // Webpack 5 is enabled by default
  // You can still use webpack 4 while upgrading to the latest version of 
  // Next.js by adding the "webpack5: false" flag
  webpack5: false,
}

You can use webpack 4.

yarn add webpack@webpack-4

0
votes

Global CSS Must Be in Your Custom <App> Why This Error Occurred An attempt to import Global CSS from a file other than pages/_app.js was made.

Global CSS cannot be used in files other than your Custom due to its side-effects and ordering problems.

Possible Ways to Fix It Relocate all Global CSS imports to your pages/_app.js file.

Or, update your component to use local CSS (Component-Level CSS) via CSS Modules. This is the preferred approach.

Example:

// pages/_app.js
import '../styles.css'

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