Search code examples
reactjswebpacksassnext.jsmini-css-extract-plugin

What is the right way to incude Sass in NextJs?


When I use Sass files in NextJs, I am getting 'conflicting order' warnigs from mini-css-extract-plugin. The conflict always messes up my stylings on build. You can see the error described in the following link:

https://medium.com/iryl/control-css-imports-order-for-next-js-webpack-based-production-applications-3b69765444fd

This is an article with a solution to this issue but it talks about ordering Sass files for only one page. I'm not sure how to do order when there are multiple pages. How can I tackle the conflicting order issue?


Solution

  • if you are using nextjs 9.3 or higher you can use it like css modules. At least this is how they recommend that you do it.

    This is an example.

    You can also check the Sass support on the Next.js docs.

    -- Update

    The best way of do it it's by creating a different scss module for each component. It will look something like this.

    Components
    ├── Header   
    │   ├── Header.js
    │   ├── Header.module.css    
    ├── Footer   
    │   ├── Footer.js
    │   ├── Footer.module.css    
    ├── Nav   
    │   ├── Nav.js
    │   ├── Nav.module.css      
    

    The main idea of using css modules it's to prevent you from use a global sheet. this way the css will be optimized on the code splitting by components and you don't have to worry about declaring the same class twice, each css module file will generate a unique class name.

    I'm working on a project using css modules, the project isn't done yet but the file structure it's almost the same working with sass, you can give it a look if you want.

    https://github.com/edgarlr/portfolio/tree/main/components