Sub topic 15
Organizing a Sass project
This chapter assumes you can write mixins, functions, and maps, and that you know the basics of @use and @forward. Here you will combine them into a folder layout that stays readable as a stylesheet codebase grows. There is no single correct layout. What matters is that each file has one job, and that dependencies run in one direction.
What organization has to solve
A single styles.scss file works for a small page. As it grows, three problems appear:
- You can't find where a rule lives.
- Changing a variable has effects you can't predict.
- Two people editing the same file produce merge conflicts.
Splitting the code into partials fixes the first and third problems. The module system fixes the second, because every file states what it depends on.
A folder layout
A common layout groups partials by role. It is a simplified version of the "7-1 pattern", which uses seven folders and one entry file.
styles/
main.scss
abstracts/
_index.scss
_tokens.scss
_functions.scss
_mixins.scss
base/
_index.scss
_reset.scss
components/
_index.scss
_card.scss
_button.scssEach folder has a purpose:
| Folder | Contains | Emits CSS? |
|---|---|---|
| `abstracts/` | Variables, maps, functions, mixins | No |
| `base/` | Resets and element defaults such as `body` and `a` | Yes |
| `components/` | One partial per UI component | Yes |
The abstracts/ folder is the important one. If it emits no CSS, any file can load it as often as it likes without duplicating output. Real projects often add layout/, pages/, or vendor/ folders. Add them when a group of files needs a name, not before.
Index files and the dependency direction
A partial named _index.scss is loaded when you write @use with just the folder name. @use 'components' loads components/_index.scss. Each folder's index file forwards its siblings, so the folder acts as one module.
The rule is that arrows never point back up. abstracts/ loads nothing from components/. A component never loads another component's internals. If you break this rule, you get circular dependencies, and Sass reports an error.
The abstracts layer
Start with the tokens:
// abstracts/_tokens.scss
$space: 8px !default;
$primary: #3366cc !default;
$breakpoints: (
sm: 36rem,
md: 48rem
) !default;The !default flag lets a consumer override a value at load time, which is covered below. Next, the function and the mixin:
// abstracts/_functions.scss
@use 'sass:math';
@function rem($px, $base: 16) {
@return math.div($px, $base) * 1rem;
}// abstracts/_mixins.scss
@use 'sass:map';
@use 'tokens';
@mixin respond($name) {
@media (min-width: map.get(tokens.$breakpoints, $name)) {
@content;
}
}The mixin loads tokens with @use because each file must declare what it needs. Nothing leaks in from a neighboring file. Then the index file combines the three:
// abstracts/_index.scss
@forward 'tokens';
@forward 'functions';
@forward 'mixins';@forward re-exports a module's public members without making them usable in the forwarding file itself. Anyone who loads abstracts sees $space, $primary, $breakpoints, rem(), and respond() under a single namespace.
Using the layer from components
// components/_card.scss
@use '../abstracts' as ds;
.card {
padding: ds.$space * 2;
font-size: ds.rem(24);
border: 1px solid ds.$primary;
@include ds.respond(md) {
padding: ds.$space * 3;
}
}The as ds clause shortens the namespace. Use a short, consistent name across the project so a reader recognizes it. The compiled output is:
.card {
padding: 16px;
font-size: 1.5rem;
border: 1px solid #3366cc;
}
@media (min-width: 48rem) {
.card {
padding: 24px;
}
}Paths in @use are relative to the file that contains them, so ../abstracts works from any component. Don't write the path from the project root.
The component index and the entry file finish the wiring:
// components/_index.scss
@forward 'card';
@forward 'button';// base/_index.scss
@forward 'reset';// main.scss
@use 'base';
@use 'components';Order matters here. Sass emits CSS in the order modules are first loaded, so base comes before components in the output. Put the lowest-specificity code first and component rules after it, so resets never override components.
Compile and watch the project with:
sass styles/main.scss dist/main.css
sass --watch styles:distWith a folder as input, Sass compiles only the non-partial files. That produces dist/main.css and ignores every file that starts with an underscore.
Configuring a module at load time
Because the tokens use !default, the entry file can change them without editing the partial:
// main.scss
@use 'abstracts' with (
$primary: #aa3355,
$space: 10px
);
@use 'base';
@use 'components';The configuration passes through @forward to tokens. Two rules cause most of the errors here:
- A module can be configured only the first time it loads. If any earlier file already loaded
abstractswithout configuration, Sass raises an error. - Only variables marked
!defaultcan be configured.
Put the configured @use first in the entry file, so it is the first load.
Keeping members private
Start a member's name with - or _ to make it private to its file. Other modules can't see it, even through @forward.
// abstracts/_functions.scss
@use 'sass:math';
$_base: 16;
@function rem($px) {
@return math.div($px, $_base) * 1rem;
}Use this for helpers and internal constants. The public surface of a module then stays small, and you can rename private members without breaking callers.
Common errors
- "There is already a module with namespace..." Two
@userules in one file produce the same namespace. Give one of them anasname. - "Undefined variable" after a refactor. The variable lives in a module the file doesn't load. Add a
@usefor it. Loading it inmain.scssis not enough. - Duplicated CSS. A partial that emits rules (a component, say) is loaded from several files. Modules that load several times are emitted once, but a copy-pasted
@includeof a rule-generating mixin duplicates output. Keep rule-emitting code in one partial and load that partial from the entry file only. - Name collisions with
as *.@use '../abstracts' as *;removes the namespace, which is convenient. When two modules export the same name, Sass reports an error. Reserveas *for the one module that every file needs, or avoid it. - A forward chain hides the origin. When a variable comes through three
@forwardrules, finding its definition takes effort. Keep chains to one level: a folder index forwards its own files.
When to split further
Add a new partial when a file passes roughly 200 lines, or when two unrelated concerns share a file. Add a new folder when you have several partials with a shared role and a name for that role. Splitting too early produces many tiny files with one rule each, which is harder to navigate than one clear file.
Exercise
In the example project, components/_button.scss needs the respond mixin and the $primary color. What must its first line be, and what two things would you write to use them?
Show answer
The first line is @use '../abstracts' as ds;. Then call the mixin with @include ds.respond(md) { ... } and read the color as ds.$primary. Without the @use line, Sass reports an undefined mixin and an undefined variable, because loading abstracts in main.scss does not make it visible inside other files.
Exercise
You add @use 'components'; above @use 'abstracts' with ($primary: #aa3355); in main.scss, and the build fails. Why, and how do you fix it?
Show answer
components loads abstracts first, without configuration, and a module can be configured only on its first load. Move the configured @use 'abstracts' with (...) above every other @use, so it is the first load.