How to use Node-sass to watch and compile scss

If you want to watch and compile your SCSS code to regular css, a very easy way to do this is with the npm package called Node-sass.

Compiling SCSS with Node-sass

  1. Create your project and cd into it.

  2. Make sure you have npm installed. You can check by typing npm --version in your terminal. If you get a version (mine is currently 6.13.6 but as long as a version appears it should work)

  3. Type and enter npm init -y to create a package.json file.

  4. Type and enter npm install node-sass. This installs the node-sass library.

  5. Open the package.json file. You will see a field that says “scripts”. Feel free to delete the “test” script. Replace it with "sass": "node-sass -w scss/main.scss css/style.css". It should look like the screenshot.

    Script in Package JSON for node-sass

    Let’s break "sass": "node-sass -w scss/main.scss css/style.css" down.

    “sass” is the name of the command. So in the next step, when you write npm run sass it will execute the sass command which runs "node-sass -w scss/main.scss css/style.css".

    The -w flag stands for watch which means it will keep watching for any changes.

    scss/main.scss is the file it will watch. This will be where you have your main scss file.

    The css/style.css is the folder and file where the sass code will be compiled into.

  6. Create a folder named css. This is where the sass code will be compiled into (as specified in the previous step)

  7. Write some sass styles in scss/main.scss. Now in the terminal run npm run sass. This should compile all the code from scss/main.scss into the css/style.css.

    Your file structure should look like this:

    File structure for node-sass to compile

That’s it! Thanks to the -w flag every time you make a change in the main.scss file, it will automatically watch for changes and save it inside the css/style.css.

Remember to link to the css/style.css file in your HTML. So if you have the same file structure as in the screenshot, your index.html should link to <link rel="stylesheet" href="/css/style.css" />.