To use npm (to install Sass), we first have to install Node.js, which we can easily do. Go to the official site and download the related installer (based on the operating system) or use your command line package managers like Homebrew or Chocolatey.
After the installation, we can access the npm command to init new projects and manage dependencies. The initialization means creating the package.json
file where we store our configuration.
Open your terminal, navigate to the project root and run:
npm init
Answer the asked questions (which you can modify later) or/and press enters. After the initialization, our package.json
file will look something like this:
{
"name": "sass-compile",
"version": "1.0.0",
"description": "A simple sass compile config.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Adam",
"license": "ISC"
}
To install Sass, we have to run the following npm command:
npm install sass --save-dev
The –save-dev
flag means that Sass is a development dependency (as you will see in your package.json
, it is under the devDependencies
object).
Now we have the Sass functionality with access to the previously mentioned CLI with its commands.
We can add any new script under the scripts object. Just remove the default one (named test) and add the following:
"scripts": {
"sass-dev": "sass --watch --update --style=expanded assets/scss:assets/css",
"sass-prod": "sass --no-source-map --style=compressed assets/scss:assets/css"
}
As you see, we set up two scripts to compile Sass:
What is a source map? A particular file that allows the browser to map back from the processed, concatenated files to the original ones. It is helpful because we can see the original file names when we debug the CSS in the developer tools.
Our project’s folder structure (should) look like this:
sass-compile/
├── assets/
│ ├── css/
│ │ └── main.css
│ └── scss/
│ ├── assets/
│ │ ├── _footer.scss
│ │ └── _header.scss
│ └── main.scss
├── node-modules/
└── package.json
We compile our Sass files from the scss
to the css
folder. We don’t have to specify file names explicitly (necessarily); the script will watch for all translatable files (the ones which don’t have a _
prefix).
For more information about the flags (the text in the command which stats with —), please visit the official CLI page.
As you see, the npm scripts work like an alias (right now we only use the Sass CLI). You can run any of the commands directly in your terminal (in any order or parallel), but this example doesn’t show the full potential. Please note that this article is only about about the Sass compile. Based on the different needs, it can be a little bit complicated and more structured.
After the previous steps, all we need is to run our scripts based on all needs. If you develop, then use:
npm run sass-dev
If you want to make a minified file, use:
npm run sass-prod