Search code examples
reactjswebpack-4next.js

Import css and sass files nextjs 7


I want be able to import in any file in my project the two types of files.

    import 'styles/index.scss';
    import 'styles/build/_style.css'

Its important to note im using Nextjs 7 and webpack 4 (comes with nextjs7)

In Nextjs 6 we used to use in next.config.js

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

const commonsChunkConfig = (config, test = /\.css$/) => {
  config.plugins = config.plugins.map(plugin => {
      if (
          plugin.constructor.name === 'CommonsChunkPlugin' &&
          plugin.minChunks != null
  ) {
      const defaultMinChunks = plugin.minChunks;
      plugin.minChunks = (module, count) => {
          if (module.resource && module.resource.match(test)) {
              return true;
          }
          return defaultMinChunks(module, count);
      };
  }
  return plugin;
  });
  return config;
};

module.exports = withCSS(withSass({
  webpack: (config, { isServer }) => {
      config = commonsChunkConfig(config, /\.(sass|scss|css)$/)
      return config
  }
}))

Solution

  • UDDATE March 2020

    Nextjs v9.3 Add support for sass as well. More info here

    UPDATE January 2020

    Nextjs v9.2 Added native support for CSS. More info on official docs

    To get started using CSS imports in your application, import the CSS file within pages/_app.js.

    Since stylesheets are global by nature, they must be imported in the Custom component. This is necessary to avoid class name and ordering conflicts for global styles.

    If you are currently using @zeit/next-css we recommend removing the plugin from your next.config.js and package.json, thereby moving to the built-in CSS support upon upgrading.


    This basic example works for me with having next-sass and next-css side by side

    /next.config.js

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

    /pages/index.js

    import '../styles.scss';
    import '../styles.css';
    
    export default () => {
      return (
        <div className="example-sass">
          <h1 className="example-css">Here I am</h1>
        </div>
      );
    };
    

    /styles.css

    .example-css {
      background-color: #ccc;
    }
    

    /styles.scss

    $font-size: 50px;
    
    .example-sass {
      font-size: $font-size;
    }
    

    /package.json

    "dependencies": {
      "@zeit/next-css": "^1.0.1",
      "@zeit/next-sass": "^1.0.1",
      "next": "^7.0.2",
      "node-sass": "^4.10.0",
      "react": "^16.6.3",
      "react-dom": "^16.6.3"
    }
    

    Here is what I see on the screen

    Hope this helps!

    PS there is some info on official GitHub repo as well