Milind Daraniya

Step-by-Step Guide: Setting Up SCSS to CSS Compilation

Published May 30th, 2023 18 min read

Hello web developers! Today, let's dive into creating a seamless SCSS to CSS compilation setup. SCSS (Sassy CSS) is a powerful extension of CSS that enables you to write more maintainable and organized stylesheets. However, browsers can't directly understand SCSS, so we need to compile it into regular CSS. Let's get started with this step-by-step example:

Step 1: Project Structure 
Ensure your project has the following structure:

project/
├── index.html
├── styles/
│   ├── main.scss
│   └── styles.css (will be generated)
├── scripts/
│   └── app.js
└── node_modules/

Step 2: Install Node.js and NPM 
Make sure you have Node.js and NPM (Node Package Manager) installed on your system. You can download and install them from the official website: https://nodejs.org

Step 3: Initialize Package.json 
Open your terminal, navigate to your project directory, and run the following command to create a package.json file:

npm init -y

Step 4: Install SCSS Compiler (node-sass) 
Install the node-sass package, which will handle the SCSS to CSS compilation:

npm install node-sass --save-dev

Step 5: Configure Compilation Script 
In your package.json file, add the following script under the "scripts" section:

"scripts": {
  "compile:scss": "node-sass styles/main.scss styles/styles.css"
}

Step 6: Write SCSS Code 
Now, you can write your SCSS code in the styles/main.scss file. For example:

// styles/main.scss
$primary-color: #3498db;

body {
  font-family: Arial, sans-serif;
  background-color: #f0f0f0;
}

.container {
  padding: 20px;
}

.button {
  display: inline-block;
  padding: 10px 20px;
  background-color: $primary-color;
  color: #fff;
  border: none;
  border-radius: 5px;
}

Step 7: Compile SCSS to CSS 
To compile your SCSS code to CSS, run the following command in your terminal:

npm run compile:scss

This will generate a new styles/styles.css file with your compiled CSS.

Step 8: Link the Compiled CSS 
In your index.html file, link the compiled CSS file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SCSS to CSS Compilation Setup</title>
    <link rel="stylesheet" href="styles/styles.css">
</head>
<body>
    <!-- Your HTML content here -->
</body>
</html>

That's it! You now have a working SCSS to CSS compilation setup. Every time you make changes to your styles/main.scss file, run the npm run compile:scss command to generate the updated CSS file.

This setup will streamline your development process, making it easier to work with SCSS and produce optimized CSS for your web projects. Happy coding! 🚀🎨