How to use Sass and Css on Next Js
You can use Sass in Next.js project with built-in Sass support.
No configuration required, just install the Sass package:
npm i sass
Next.js will see this dependency and enable built-in Sass loader.
You can include global styles in /pages/_app.js
.
For component or page specific Sass files you can use built-in support of CSS modules.
For example, if you have a component Button.js
you can create a Sass file button.module.scss
and include it in the component.
Tae Pak
Updated on June 13, 2022Comments
-
Tae Pak almost 2 years
I've been trying to use sass and css modules in my next.config.js, but keep running into this error:
Failed to compile. ./node_modules/@riskalyze/react-ui/node_modules/@riskalyze/calendar/assets/index.css Unknown word (1:1) > 1 | var api = require("!../../../../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js"); | ^ 2 | var content = require("!!../../../../../../css-loader/index.js!./index.css"); 3 | 4 | content = content.__esModule ? content.default : content;
After reading around on github and stackoverflow it sounds like its because I have two instances of css modules configurations in my next.config.js, but I'm unsure how to reduce that to one while still keeping this logic in tact:
config.module.rules.push({ test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader' }], });
Below is my full next.config.js
const path = require('path'); const withSass = require('@zeit/next-sass'); const withCSS = require('@zeit/next-css'); const aliasPathsToResolve = [ { name: 'react-ui', path: path.resolve(__dirname, './node_modules/@riskalyze/react-ui/') }, { name: '@babel/runtime-corejs2', path: path.resolve(__dirname, './node_modules/@babel/runtime-corejs2/') } ]; module.exports = withCSS( withSass({ cssModules: true, cssLoaderOptions: { importLoaders: 1, localIdentName: '[name]__[local]___[hash:base64:5]' }, webpack: (config, { defaultLoaders }) => { config.module.rules.push({ test: /\.+(js|jsx|ts|tsx)$/, loader: defaultLoaders.babel, include: /react-ui/ }); config.module.rules.push({ test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader' }], }); aliasPathsToResolve.forEach(module => { config.resolve.alias[module.name] = module.path; }); return config; } }) );
-
Nikolai Kiselev almost 4 years
-
Tae Pak almost 4 yearsNikolaiKiselev what if I have a bunch of scss files for each different component in the app?
-