Using SASS/SCSS in Vite

Tutorial 3 of 5

Using SASS/SCSS in Vite

1. Introduction

Goal

In this tutorial, our goal is to guide you on how to use SASS/SCSS, which are CSS preprocessors, in a Vite project.

Learning Outcomes

By the end of this tutorial, you should be able to:

  • Understand the use of SASS/SCSS.
  • Install and configure SASS/SCSS in a Vite project.
  • Write and compile SASS/SCSS code in Vite.

Prerequisites

You should have a basic understanding of:

  • CSS
  • JavaScript
  • NodeJS
  • Basic command-line operations

2. Step-by-Step Guide

Installation

To work with SCSS, we need to install the SASS package. Navigate to your project directory and run the following command:

npm install -D sass

Configuration

After installing sass, create a style.scss file in your src folder and write some SCSS in it:

$color: red;

body {
  background-color: $color;
}

In your JavaScript or Vue file, import the SCSS file:

import './style.scss'

Vite will automatically compile and include the CSS in your application.

3. Code Examples

Example 1: Variables

SCSS allows you to use variables. Here is a simple example:

$font-size: 16px;
$text-color: blue;

body {
  font-size: $font-size;
  color: $text-color;
}

This will compile to:

body {
  font-size: 16px;
  color: blue;
}

Example 2: Nesting

SCSS lets you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML.

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }

  a {
    display: block;
    padding: 0 10px;
    color: #333;
  }
}

This will compile to:

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 0 10px;
  color: #333;
}

4. Summary

In this tutorial, we have covered:

  • What SASS/SCSS is and why we use it.
  • Installing SASS in a Vite project.
  • Writing and importing SCSS code.
  • Examples of SCSS features.

From here, you can learn more about other SCSS features like mixins, functions, and more. A good resource for this is the SASS documentation.

5. Practice Exercises

Exercise 1: Create a SCSS file with variables for colors and font sizes, and use them in your styles.

Exercise 2: Nest CSS selectors in your SCSS file to style a complex HTML structure.

Solutions:

  1. See the 'Variables' example in the 'Code Examples' section.
  2. See the 'Nesting' example in the 'Code Examples' section.

Remember, the more you practice, the more comfortable you will become with SCSS. Happy coding!