The previous article explained what SASS is and why it’s preferable to use it rather than CSS. Right now, we are about to learn how to include it in our project.
Browsers won’t understand sass files since, as we all know, they only understand HTML, CSS, and JS. Therefore, in order to make it simple for browsers to grasp, we need to compile Sass scripts into CSS files.
In the next few lines, we will discuss 3 methods to compile Sass to Css
#1. Command Line
One of the simplest ways to compile Sass into CSS is by using the node-sass package.
node-sass can be installed on Windows, Mac OS X, Linux, and Unix operating systems. It can also be installed through the Node Package Manager (NPM). The installation process for both methods is quite simple.
To install node-sass using NPM, we need to install node.js first on our machine, then open node terminal and follow these steps:
1-Run node --version
to confirm that the node has been set up properly.
node --version
> Expected: v16.16.0 or any other version
2-Create a package.json file.
npm init -y
> -y means initiate with the default settings.
3-Install sass-node
npm install -g sass-node
This will download the package from npm’s repository and install it globally on your system.
4-Get node-sass working
In package.json file, replace this script 👇
"test": "echo "Error: no test specified" && exit 1"
with this one 👇
"scripts": {
"sass": "node-sass -w scss/ -o css/ --recursive"
},
Sass script will automatically convert any sass/scss files available in the scss/ folder to css files and place them in the css/ folder.
5-Run the sass script
npm run sass
Congratulate 🎉 you have setup sass successfully.
Now, if you copy & paste this Scss code in your local Scss file
$socails : facebook twitter youtube;
@each $item in $socails {
.#{$item}-img{
background: url('../images/image-#{$item}.png');
}
}
it will be compiled to
.facebook-img {
background: url("../images/image-facebook.png");
}
.twitter-img {
background: url("../images/image-twitter.png");
}
.youtube-img {
background: url("../images/image-youtube.png");
}
#2 VS Code Extensions
live-sass is one of the most efficient VS code extensions that is used in sass compilation.
#3 Online Compilers
There are some online tools, such as sassMeister that compile Sass without any installs.
Now, it’s time to go deeper with sass. In the next article, we will learn more about sass syntax.