I’m a big fan of Gulp, I’ve been using it for over two years recently I found myself using NPM scripts for my Javascript Applications. So I decided to see if it possible for me to use NPM also to compile my sass files.

First thing before we start you to need to have NodeJS installed on your machine.

The script above is an extracted version of one my gulp scripts for compiling my stylesheets. What the code snippet above does is first imports my gulp plugins. In this case I’m using gulp, gulp-sass and gulp-sourcemaps. The sass task sets the sourcemaps then compiles my sass files into stylesheets. Finally the watch task checks for changing in my sass file and then runs the sass task.

NPM Script

The script for compiling the stylesheet goes into the package.json if you haven’t got one already let’s create one. From the command line type the following below.

npm init -y

To compile the stylesheets we be using node-sass. Gulp-sass the package which I use in my Gulp tasks is a wrapper for node-sass so this should cover us for compiling our sass files. Again from the command line lets install the package.

npm install node-sass --save

Now we going to open up the package.json file in our root directory. Under scripts in the json file we going to create our own script called sass. What the script does run node-sass package on my sass file and outputs it to the css folder.

To run the script we just created from the command line type the follow below. Then review the stylesheet.

npm run sass

That compiled the sass file. But based on my previous gulp script there some more options which we need to enable like compressing the css output and sourcemaps. So lets starts by compressing the output. Back to our sass script we will add in the compress flag. Add the following below to your code and run the script again

Now we going to add back in sourcemaps, this time we being using the sourcemaps which are baked into node-sass. If we refer to the node-sass documentation. To enable source maps we add the parameters below.

I’ve managed to replicate my current gulp sass task. Now we just need to create a watch script to watch our sass files for a change. To do this we going to create another script this time called watch:sass. This will watch the sass folder for any changes and then will run sass script.

To run the watch:sass script from the command line type the following below. Now make changes to your sass files as you can see the stylesheet gets compiled.

npm run watch:sass

After writing this script it’s very straight forward to replace gulp for using NPM Script. I have several other gulp tasks that I use in my workflow I need to investigate the process of converting these into NPM scripts. But I would most likely do these on new projects as the saving’s I would get on existing projects is very small.