Compiling SASS to CSS

Tutorial 4 of 5

Introduction

In this tutorial, we'll learn how to compile SASS (Syntactically Awesome Stylesheets) to CSS. Since web browsers can't interpret SASS directly, we must convert our SASS code to CSS.

By the end of this tutorial, you'll know how to setup a SASS compiler in your project and use it to compile your SASS code into CSS.

Prerequisites:
- Basic knowledge of CSS and SASS
- Node.js and npm installed on your system
- A text editor such as Visual Studio Code

Step-by-Step Guide

Step 1: Install Node.js and npm

Before we can compile our SASS files, we need to make sure we have Node.js and npm installed. You can download Node.js and npm from this link.

Step 2: Install SASS

We will use npm (Node Package Manager) to install SASS. Open your terminal or command prompt and type the following command:

npm install -g sass

This command installs SASS globally (-g) on your system.

Step 3: Write SASS Code

Create a new file with a .scss extension for your SASS code.

For instance, style.scss:

$font-stack: Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

Step 4: Compile SASS to CSS

To compile your SASS file to CSS, run the following command in your terminal:

sass style.scss style.css

This command compiles the style.scss file into style.css.

Code Examples

Here is an example of a SASS file and the resulting CSS after compilation.

style.scss:

$bg-color: #f5f5f5;
$text-color: #333;

body {
  background-color: $bg-color;
  color: $text-color;
}

After running the sass command, this is your compiled CSS:

style.css:

body {
  background-color: #f5f5f5;
  color: #333;
}

In the SASS file, we declared two variables: bg-color and text-color, and used them as the values for the background-color and color properties in the body selector.

Summary

In this tutorial, we have learned how to compile SASS files to CSS using Node.js and the SASS npm package. We wrote some SASS code, and then we used the sass command to compile it to CSS.

Next steps could include learning more about SASS features like nesting, mixins, and inheritance.

For more in-depth information about SASS, visit the official SASS guide.

Practice Exercises

  1. Create a SASS file with a few variables and selectors. Compile it to CSS.
  2. Create a SASS file that uses nesting and mixins. Compile it to CSS.
  3. Setup a "watch" task with the SASS compiler so it automatically compiles your SASS to CSS whenever you save your SASS file.

Remember to practice regularly and experiment with different SASS features. Happy coding!