Sub topic 16
Moving from @import to modules
This chapter assumes you have read the earlier chapters on variables, mixins, functions and partials. It also assumes you can compile with Dart Sass. The goal is to convert an existing @import-based codebase to @use and @forward without breaking its output.
Why @import is being retired
Sass @import behaves like pasting one file into another. Every variable, mixin and function lands in one global scope. That causes four problems:
- Name collisions. Two partials that both define
$gapsilently overwrite each other, and the last one loaded wins. - Hidden dependencies. A partial can use
$primarywithout saying where it comes from. Reordering the imports can break it. - Duplicate output. Importing the same file in two places emits its CSS twice.
- No privacy. Every helper is visible everywhere.
Dart Sass began printing deprecation warnings for @import in version 1.80.0. The feature is scheduled for removal in Dart Sass 3.0.0. The module system (@use and @forward) fixes all four problems. The built-in global functions such as darken() and map-get() are deprecated for the same reason, and you will meet them during migration.
What changes
| Behavior | @import | @use |
|---|---|---|
| Scope | Everything becomes global | Members live in a namespace |
| Loading twice | CSS is emitted twice | The file loads once, however often it is used |
| Member access | `$space` | `tokens.$space` |
| Private members | Not possible | Names starting with `-` or `_` stay private |
| Configuration | Set a variable before importing | `@use 'tokens' with ($space: 4px)` |
| Position in file | Anywhere | Before all rules except `@forward` and variable declarations |
The namespace is the last part of the URL by default. @use 'abstracts/tokens' creates the namespace tokens. You can rename it with as, or drop it with as *.
@use 'abstracts/tokens' as t;
@use 'abstracts/mixins' as *;
.box {
padding: t.$space;
@include respond(48rem) {
padding: t.$space * 2;
}
}Use as * sparingly. It brings back the collision risk that modules exist to remove.
A before and after example
Here is a small @import project.
// _variables.scss
$primary: #3366cc;
$space: 8px;
// _mixins.scss
@mixin respond($min) {
@media (min-width: $min) {
@content;
}
}
// main.scss
@import 'variables';
@import 'mixins';
.card {
padding: $space * 2;
border: 1px solid $primary;
background: darken($primary, 40%);
@include respond(48rem) {
padding: $space * 3;
}
}Here is the module version. The partials get !default on values that callers may configure. The color function now comes from sass:color.
// _variables.scss
$primary: #3366cc !default;
$space: 8px !default;
// _mixins.scss
@mixin respond($min) {
@media (min-width: $min) {
@content;
}
}
// main.scss
@use 'sass:color';
@use 'variables' as v;
@use 'mixins';
.card {
padding: v.$space * 2;
border: 1px solid v.$primary;
background: color.adjust(v.$primary, $lightness: 40%);
@include mixins.respond(48rem) {
padding: v.$space * 3;
}
}Two details are easy to miss. First, the call is @include mixins.respond(...), so the namespace goes before the mixin name, not before @include. Second, darken($primary, 40%) has no exact one-word replacement. color.adjust with a negative or positive $lightness is the closest direct equivalent. color.scale is often a better choice because it scales relative to the current value instead of adding to it.
Configuring a module
With @import, you customized a library by defining a variable before the import. With modules, you pass values through with.
@use 'variables' with (
$primary: #aa3366,
$space: 4px
);A few rules apply:
- Only variables marked
!defaultin the target file can be configured. Configuring any other variable is a compile error. - A module is configured the first time it is loaded. If another file already loaded it without configuration, a later
withfails with an error. - The safest pattern is one entry file that configures a module before anything else uses it.
Bundling with @forward
Writing a dozen @use lines in every file gets tedious. An index partial can gather several modules and re-export them with @forward. Sass resolves @use 'abstracts' to abstracts/_index.scss automatically.
// abstracts/_index.scss
@forward 'variables';
@forward 'mixins';// components/_card.scss
@use '../abstracts';
.card {
padding: abstracts.$space;
@include abstracts.respond(48rem) {
padding: abstracts.$space * 2;
}
}@forward does not make members available to the forwarding file itself. It only passes them on. If the index also needs to use a variable, add a separate @use.
Forwarding can also filter and rename members:
@forward 'variables' show $primary, $space;
@forward 'internal-helpers' hide debug-log;
@forward 'mixins' as mx-*;The last line makes respond reachable as abstracts.mx-respond. Prefixes help when two forwarded modules would otherwise clash.
Migrating step by step
The official sass-migrator tool does most of the mechanical work.
npm install -g sass-migrator
sass-migrator module --migrate-deps --dry-run --verbose src/main.scss
sass-migrator module --migrate-deps src/main.scssThe first command previews the changes. The second applies them. --migrate-deps follows the imports and converts every partial, not only the entry file. Run it from a clean Git state so you can review the diff.
After the migrator finishes, check these areas by hand:
- Generated names. The migrator may pick namespaces you dislike. Rename them with
as. - Global functions. Look for remaining
darken,lighten,map-get,percentageand/used for division. Replace them withsass:color,sass:mapandmath.div. - Mutating variables from outside. Code like
$primary: red;after an import used to change the library's value. Convert it towith (...), or assign explicitly withtokens.$primary: red;. - Plain CSS imports.
@import url(...)and@import 'file.css'stay as normal CSS imports. They are not Sass imports and are not deprecated. @extendacross files.@extendworks only with selectors from modules that the current file loads, directly or indirectly. A missing@usecan turn an extend into an error.
Migrating gradually
You do not have to convert everything at once. The two systems interoperate:
- A file using
@usecan load a file that still uses@import. Its global members become members of the module. - A file using
@importcan load a file that uses@use. Only the members that file defines or forwards become global, and its dependencies stay namespaced. - Convert from the leaves up. Start with partials that import nothing, then move toward the entry file.
- To keep old and new code working together, add
@forward 'file' as prefix-*and@importthe same file under aprefix-name in the legacy code.
Common errors after migrating
Undefined variable.The file uses$spacewithout a namespace. Add the namespace or an@usefor the module.@use rules must be written before any other rules.Move the@uselines to the top of the file. Only comments,@forwardand variable declarations may come before them.This variable was not declared with !default in the @used module.Add!defaultin the partial, or stop configuring that variable.The same module is loaded with different configurations.Two@use ... withstatements disagree, or a second one came after an unconfigured load. Move the configuration to the first load.Undefined function.A global function was removed from your code, or the module needs an@use 'sass:...'.
Exercise
A file _buttons.scss contains @use 'tokens';, and the code .btn { padding: $space; }. The compiler reports "Undefined variable." Give two valid ways to fix it, and name one risk of the second.
Show answer
First, use the namespace: padding: tokens.$space;. Second, load the module without a namespace with @use 'tokens' as *; so $space works unqualified. The risk of as * is that its members enter the file's scope directly, so they can collide with local names or with other modules loaded the same way. That brings back the collision problem that @import had.
Exercise
You change @use 'tokens'; to @use 'tokens' with ($space: 4px); in main.scss, but the compiler fails with an error about configuration. _tokens.scss starts with $space: 8px;. What is wrong, and what is the fix?
Show answer
A module can only be configured for variables declared with !default. Change the line in _tokens.scss to $space: 8px !default;. If another file loaded tokens before main.scss reached this @use, also move the configured @use to run first, because a module is configured only on its first load.