How to use node-sass to compile Sass files in an npm script (2019 Update)

how to compile the popular Sass preprocessor into regular CSSWhile there are numerous options for choosing how to compile the popular Sass preprocessor into regular CSS, a compiler that utilizes the LibSass engine has increasingly become more common. Initially written in Ruby, using the original Ruby gem or a Ruby-based program such as Compass to compile Sass quickly became host to a variety of criticisms regarding its slow compiling time and overall speed. In answer to the performance complaints, the original Sass engine was ported over to C/C++ as LibSass, with numerous wrappers available to run the Sass engine in just about every popular programming language. This tutorial will introduce the Sass programming language and also provide a step-by-step guide to using the node-sass wrapper to compile your Sass code, directly as an npm script. Note that node-sass is intended to be used with .scss files rather than .sass, the former being the more common and popular option.

About Sass CSS Preprocessor

Sass, or Syntactically Awesome Style Sheets, is an example of a CSS preprocessor, which enables developers to create code in one language and then “translate” it into CSS. Licensed under MIT, Sass boasts its compatibility with CSS and highly feature-rich programming language, making it a perfect combination of the characteristics of a stylesheet and a computer program. In this sense, it is a powerful tool for website developers who are familiar with programming, although anyone can learn how to operate Sass with enough practice. Also, there are two slight variations of the Sass language, the Sassy CSS (abbreviated as SCSS) and simply Sass. While Sassy CSS is much more similar to CSS in terms of syntax, Sass is a better preference for developers who are more concerned about convenience. The latter option omits curly brackets and semicolons and instead reads code based on indentations.

It is important to note that most developers and online documentation sources will use SCSS syntax because of its similarity to CSS. In addition, you should note that web browsers do not read Sass or SCSS files. Therefore, you must convert all SCSS/Sass files into CSS before publishing your website onto the Internet. For an explanation on how to do this, please refer to “Converting between SCSS to CSS files” below.

Setting Up Sass

Install Node.js and NPM

If you don’t already have Node.js installed, you can download the latest version on its official site. If you are not familiar with this term, Node.js is a popular runtime environment for Javascript. Node comes pre-packaged with npm, the official Node package manager which gives developers access to open source Javascript code, so it will be installed at the same time. (If you are interested or need to install npm separately, you may do at the official website for npm.) To check that npm was installed successfully, run npm -v in your terminal to confirm the version of npm currently on your computer. At the time this blog post was updated, the latest version of npm released is 6.7.0.

Install node-sass

Once you have npm installed, it’s time to install node-sass. You can do so by running npm install -g node-sass in your terminal to install the package globally (i.e. available across your entire system), or run npm install node-sass without the -g flag to only install to your current directory.

Project setup with package.json

Assuming node-sass is now installed globally, it’s time to make or choose a project directory where we want to watch our Sass files. Navigate to your project directory, and initialize the project with a package.json file, by running npm init.

Setting Up Sass

You’ll be prompted to input a variety of details on the project, such as package name, version, description and other details. You can either fill in this info now or just hit Enter for each of these prompts and fill it in later.

Install Node.js and NPM

After cycling through each of the prompts, there will be a prompt to confirm the entered info (or info left blank). Hit enter once more and the package.json file will be created.

Install node-sass

Add the node-sass script

Open the package.json file in your text editor of choice, and add the following line inside the "scripts" object:

"scss": "node-sass" --watch assets/scss -o assets/css"

The line above tells npm to run a script, watching for changes to any .scss files in the assets/scss directory and commit those changes to corresponding CSS files in a assets/css directory. You should change the paths for your directories accordingly.

Your edited package.json file should look something like this:

{
  "name": "sass-ex",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "scss": "node-sass" --watch assets/scss -o assets/css"
  },
  "author": "",
  "license": "ISC"
}

 

Save the file and close it. Now in the root of the project directory, run npm run scss to start watching for any changes to your .scss files.

Alternative Ways of Installing Sass

It is important to note that there are various alternative methods of installing Sass. For instance, you can install Sass via paid and free applications such as CodeKit and Scout-App. In addition, you can also install Sass by downloading the package from the official Github site and adding it directly to your path.

Overview of Designing with Sass

As mentioned previously, Sass comes with many beneficial features that make it a powerful tool for website developers. Sass adopted these traits from basic programming language, some of which this blog post will discuss below. For a more thorough guide of these features and how to implement them in your code, visit the official guide on the Sass website.

Variables

Just like in programming, you can create and implement variables in Sass throughout your style sheet. This is extremely convenient because if there is a certain style you want to use throughout your website (for example, a type of font package, color, etc.), you can simply store it in a variable and use it throughout your stylesheet. Declaring a variable in Sass is especially straightforward for programmers because it is conceptually identical to Javascript. For instance, if you declare $primary-color: #525; ($variable: value;) at the beginning of your stylesheet, then you can simply input $primary-color for any color value.

Nesting

HTML and most popular programming languages maintain a clean structure with the use of indentations or nesting. On the other hand, a traditional CSS stylesheet is rather one lengthy, cluttered list of various styles. But with Sass, you can enhance the readability of your stylesheets by placing different blocks of code within other code. For instance, inside of the styling of a traditional nav bar, you can nest the code for designing the placement of the list items and the style of the text. This visual hierarchy of code through nesting is another reason that many developers will gravitate towards the use of Sass in their websites.

Importing SASS files

As your websites and the HTML documents become more complex, this will typically result in a parallel growth of your CSS files. However, creating more styles will eventually clutter your stylesheets, making it difficult to maintain and write in an orderly fashion. Fortunately, by using Sass, you can divide up your stylesheets into multiple Sass files. When you are ready to launch your website, you can combine the multiple SCSS files into one master stylesheet, and then link this to your HTML document through the importing feature. Unlike CSS, it will only require one HTTP request to load the single Sass “master” stylesheet; in CSS, the client makes an HTTP request for each stylesheet imported. To import a stylesheet, simply write keyword @import followed by the name of the sub-stylesheet in quotation marks (@import “stylesheet”;). This is another key feature of Sass that simplifies the process of managing a website.

Using Mixins

Most people with programming experience are familiar with writing functions or methods in their programs; however, traditional CSS files do not support this feature. Fortunately, Sass allows developers to write mixins, or a group of CSS declarations that are grouped together and can be used repetitively anywhere on your stylesheet. A mixin is essentially the equivalent to a function; it can accept an input value and plug it into the CSS declarations grouped inside the mixin. To create a mixin, simply write @mixin mixinName(value) followed by the CSS declarations that use the inputted value. To call on this mixin in your stylesheet, write keyword @include followed by the mixin’s name and value (if applicable). Mixins in Sass undoubtedly pave the way for powerful and efficient website design by creating less repetitive code.

Sass allows developers to write mixins, or a group of CSS declarations

Using Inheritance and Other Directives

Another powerful programming feature that you can implement through website development with Sass is inheritance. You can refer to this as “extending” selectors in Sass. With the use of @extend, selectors can inherit the CSS properties of other selectors, thus simplifying your code immensely by removing the need for repetitive code. This creates more flexibility in your stylesheet by only “turning on” a selector with the keyword @extend. To use this feature, simply create a selector with the % symbol in front to indicate that the CSS properties in this selector can be extended. Now, when you are creating another selector, you can call @extend %selectorName; and its properties will be inherited by that new selector.

While the @extend function is wildly popular among Sass advocates, there are many basic programming functions that have been integrated into the Sass language. For instance, most programmers are familiar with the use of conditional statements. Now, Sass developers can use @if and @else directives which will lead to much more powerful website development. Similarly, those who are familiar with the traditional for and while loops can replicate these Java functions with the @for and @while directives.

Using Operators

Programmers use mathematically driven algorithms all of the time. On the other hand, there is practically no usage of math involved in traditional CSS design. Luckily, Sass allows developers to use basic operators (+, -, *, /, %) to calculate pixel or percentage values in CSS declarations. It is a small but highly practical tool for designers who wish to create more complex websites. According to the official documentation for Sass, there is also a library of math-driven functions that Sass developers can use. Actually, most programmers are probably familiar with many of these functions in the library. It includes functions such as abs($number) to find absolute value, min($numbers…) to find the smallest of multiple values, and random() to return a random numerical value. To view all of the functions available on Sass, visit the official documentation site for Sass.

Converting between SCSS to CSS files

After you have finished designing your HTML elements using Sass, it is time to finally publish your website. However, you cannot directly use the SCSS files when loading your website. Instead, you must convert your files to CSS. With the Sass gem, which can be installed through the command line, there a variety of executables available. If you do not have the Sass gem installed, you may also run the Sass executables with another source.

  • sass or $ bundle exec sass: Used to convert a source Sass file into a CSS file. Run sass --help for more for more instructions.
  • sass-convert or $ bundle exec sass-convert: Used to convert between Sass, SCSS, and CSS files. Run sass-convert --help for more instructions. This is a perfect executable for existing projects that you would like to switch over to SCSS format.

Converting between SCSS to CSS files

Other CSS Preprocessors

Stylus

Stylus is another highly popular alternative for a CSS preprocessorModeled after Sass, Stylus is another highly popular alternative for a CSS preprocessor. A particularly useful feature that draws many users towards Stylus is its highly dynamic and flexible language and syntax. Users have the option of omitting punctuation such as curly braces, colons, and semicolons. They can even omit certain keywords (for example, @mixin) if they prefer. Similar to Sass, Stylus integrates many powerful programming features such as functions/mixins, variables, iteration, and inheritance. A particularly useful feature in Stylus is the CSS literal, indicated by @css. This keyword can be used to revert back to CSS type if Stylus is unable to accommodate a request.

Less

Less, which stands for Leaner Stylesheets, is another CSS preprocessorLess, which stands for Leaner Stylesheets, is another CSS preprocessor option that is very similar to its alternatives. It offers many built-in programming features. This includes creating variables, using mixins, nesting your code, and utilizing a library of built-in functions. Unlike Stylus, Less is more strict in its syntax. In fact, it practically replicates the syntax of traditional CSS code. Based on your personal preferences, you may view this as an advantage or a disadvantage.

Conclusion

All in all, Sass is a great tool for website developers who are looking to enhance their web design with basic programming functions. Not only is installation straightforward, but the Sass language and syntax is quick to learn. The various programming functions, such as mixins and variables, and the visual hierarchy of Sass create more efficient and maintainable stylesheets. I hope that this tutorial for installing Sass and overview of Sass features will guide you as you experiment with this innovative CSS preprocessor.

Resources

2 Comments

  • Garrett Corwin February 15, 2019 at 3:08 pm

    I’ve done this and many varieties of this with no luck. Terminal always throws the same error: missing script:scss. I have a feeling it’s because I’m using node-sass 4.11.0 and there have been changes since most of these guides came out. Any thoughts? Thanks

    • Jordan April 15, 2019 at 2:39 pm

      This is because there is a typo in setting up the script. There should not be a quotation mark after node-sass. So, instead of “scss”: “node-sass” –watch assets/scss -o assets/css”, the line should read
      “scss”: “node-sass –watch assets/scss -o assets/css”

Post a Comment

Comments are moderated. Your email is kept private. Required fields are marked *

© 2019 Sunlight Media LLC