Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Installing and compiling

Sass is installed as an npm package and run with the sass command. The command reads a .scss file and writes a .css file next to it or into another folder. You need Node.js 20 or newer.

Installing

Create a folder for the site and install Sass into it as a development dependency:

mkdir site
cd site
npm init -y
npm install --save-dev sass
npx sass --version

npm init -y creates package.json, and the last command prints the installed version, for example 1.93.2. npx runs the sass program from the project's node_modules.

Project layout

Sources live in styles/, compiled files go to css/, and the page links only the CSS:

site/
├── index.html
├── css/
│   └── main.css      ← created by Sass
├── styles/
│   └── main.scss     ← you edit this
└── package.json

Create styles/main.scss:

// styles/main.scss
$radius: 8px;
 
.card {
  padding: 16px;
  border-radius: $radius;
}

Compiling

The command takes the source file and the output file:

npx sass styles/main.scss css/main.css

The css folder appears with main.css inside:

.card {
  padding: 16px;
  border-radius: 8px;
}

In index.html link it as usual: <link rel="stylesheet" href="css/main.css">.

Watching for changes

Running the command after every edit is tedious. The --watch flag keeps Sass running and recompiles each time you save:

npx sass --watch styles/main.scss css/main.css

After each save the terminal prints a line like Compiled styles/main.scss to css/main.css. Stop it with Ctrl+C.

Source maps

Next to main.css Sass also writes main.css.map — a source map. It tells the browser which line of which .scss file each rule came from, so DevTools shows main.scss:4 instead of a line in the compiled file. To connect the two, Sass adds a last line to main.css: /*# sourceMappingURL=main.css.map */. Turn maps off with --no-source-map; the examples in this course show the CSS without that line.

Scripts in package.json

Save the commands as npm scripts so you do not have to remember the flags:

{
  "scripts": {
    "sass:dev": "sass --watch styles/main.scss css/main.css",
    "sass:build": "sass --no-source-map styles/main.scss css/main.css"
  }
}

Now run npm run sass:dev while you work. Inside scripts npx is not needed.

Common mistake

Do not edit css/main.css by hand. On the next compile Sass overwrites it, and your changes are lost without warning. Make every change in styles/; treat css/ as a generated folder.

Thanks for reading!

Donate to the site — we work hard for you.