Styling is a core part of designing application pages. Whenever I start working on Next.js, I usually find myself wasting some time googling how to configure SCSS in my project. So, in order to save your precious time, I have decided to pen down this issue as a reference.
Although Next.js offers a really sophisticated plugin next-sass for compiling sass files but this plugin fails to parse .eot and .woff files. So for parsing all our sass and font files, we have to add custom Webpack configuration inside next-sass.
Next-sass compiled stylesheet to .next/static/css. Next.js will automatically add the CSS to your HTML files.
Step 1: Install Dependencies
Let’s start by installing dependencies.
First, we need to install next-sass.
`npm install --save @zeit/next-sass`
Next-sass plugin used node sass so we have to install node-sass as well.
`npm install --save @zeit/node-sass`
Step 2: Create the Next Config File
Now, create the next.config.js file in the root of your project directory. Next.js automatically reads all configurations from this file. So you just need to add the configurations here and export them.
Step 3: Add Customize the Configuration
Now, We have to add customized configuration inside next-sass to make it work fully and functional for compiling SASS and font files.
This configuration is capable of parsing following file types:
Sass and css files
Font files (.eot, .woff, .woff2)
Image files (.png, jpg, .gif, .svg)
const withSass = require('@zeit/next-sass');
const withCSS = require("@zeit/next-css");
module.exports = withCSS(withSass({
webpack (config, options) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000
}
}
});
return config;
}
}));
Great! You now have sass configured and I now have my permanent reference. Cheers!
Top comments (13)
Package @zeit/node-sass doesn't seem to exist. Guess it should be just "node-sass" :)
why is nested SCSS not working?
.loginForm{
width:300px;
}
how to add config css modules ?
You Can just Add
// next.config.js
const withSass = require('@zeit/next-sass')
module.exports = withSass({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]___[hash:base64:5]",
}
})
My hero! Been tinkering with this for quite some time, thanks for saving my sanity!
thank you very much, you saved my life!!!!
Thanks but a little more explanation would be nice, like why is different than the vanilla configuration in the docs and what is url-loader and limit doing?
However, sass is not modular. Is it?
Doing this in any scss file will affect the entire document:
div {
background: red
}
Thanks guy!
Thanks this helped...🚀
This is works for me.
sudo npm install --save-dev --unsafe-perm node-sass