reactjsnext.jswebpack-loadercss-import

How to import external css file in nextjs app


I am working on react based nextjs app. Some npm packages are using external css import. I am getting error like

Module parse failed, you may need an appropriate loader to handle this file type.

How can I support css import from external packages in my nextjs app. I have checked somewhere by making change in next.config.js, it works. But I am unable to find the proper one.It would be great if someone can help me around this.


Solution

  • For Global CSS

    To add global css, inside the file pages/_app.js use import '../styles.css' or to import from node_modules, use something similar to import 'bootstrap/dist/css/bootstrap.css'

    For Component Level CSS

    Next.js supports CSS Modules using the [name].module.css file naming convention. CSS Modules locally scope CSS by automatically creating a unique class name. This allows you to use the same CSS class name in different files without worrying about collisions.

    If you have a component called Button inside Button.js, create a file called Button.module.css for the css file. Then you can import it to the Button component by import styles from './Button.module.css'

    Documentation

    Old Answer

    You can add the css file in head of nextjs.

    import Head from 'next/head'
    

    and in the render method, inside the return add a head tag similar to ordinary HTML, the head tag should be inside a div.

    <div>
        <Head>
          <title>Test</title>
          <link href="/static/master.css" rel="stylesheet" key="test"/>
        </Head>
    </div>
    

    also the css should be in static folder. Add a key to the link tag to reuse the css in multiple pages. If the key is same across pages, then the next server won't reload the css, but instead will reuse the css file.

    This way there is no need for any css packages either.