Sass Modules: Using @use for Clean, Scoped Styles
Think of `@use` as importing a JavaScript module. It loads Sass variables and mixins into a private namespace, preventing global style conflicts. Use it to structure large CSS codebases by breaking styles into logical partials.
WHY IT EXISTS The old @import rule in Sass made all variables, mixins, and functions from imported files globally available. This led to naming collisions and made it difficult to trace where a style came from in large projects. It was impossible to know which dependencies a file truly had.
THE MENTAL MODEL Treat @use like an ES6 import statement in JavaScript. You are explicitly loading a "module" (another Sass file) and its members (variables, mixins, functions) become available only within the current file, under a specific namespace. This makes dependencies clear and prevents styles from leaking into the global scope. Files intended only for import are called "partials" and their names start with an underscore, like _variables.scss.
HOW IT WORKS When you write @use 'src/corners', Sass loads the file _corners.scss. It makes any variables, mixins, or functions in that file accessible via a namespace, which defaults to the filename (corners). For example, a variable radius in _corners.scss is accessed as corners.radius. A mixin rounded is included with @include corners.rounded. Importantly, the CSS from a module is included in the final output only once, no matter how many other modules @use it.
WHEN TO USE IT Use @use as the default way to structure any modern Sass project. It's essential for building design systems, component libraries, or any large-scale application where you need to manage dependencies cleanly. It allows you to create small, focused partial files for things like colors, typography, or individual components, and then compose them together safely.
WHEN NOT TO USE IT The primary reason not to use @use is for compatibility with older Sass compilers. Only Dart Sass supports @use; LibSass and the old Ruby Sass do not. If your project is stuck on an older build toolchain that uses LibSass, you'll have to stick with the legacy @import rule and its associated problems. All @use rules must also appear at the top of a file, before any style rules.
ONE CANONICAL EXAMPLE To create a reusable, rounded button, you first define your corner styles in a partial file. File: _corners.scss $radius: 3px; @mixin rounded { border-radius: $radius; }
Then, in your main stylesheet, you @use the partial and apply its members using the namespace. File: style.scss @use 'corners'; .button { @include corners.rounded; padding: 5px + corners.$radius; }
This compiles to CSS where the button has a 3px border-radius and 8px of padding, without making $radius or rounded globally available.
Read the original → sass-lang.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.