It's not possible to use an @import
based on a condition, but there are many alternative methods you can try out. Below is a simple framework I created in the past.
@function keyFilter($iKey, $fKey, $rKey) {
@if ($iKey == $fKey) {
@return $rKey;
}
@return $iKey;
}
@function v($key) {
@return var(--#{$key});
}
//
$modes: (
"&": (
"color": #000,
),
"dark": (
"color": #fff,
),
);
//
@each $key, $map in $modes {
body#{keyFilter("[#{$key}]", "[&]", null)} {
@each $key, $value in $map {
--#{$key}: #{$value};
}
}
}
To add a new mode, simply include another map within the $modes
variable. You can create as many modes as needed. Remember that the "&"
mode represents the default mode.
$modes: (
"&": (
//...
),
"dark": (
//...
),
//...
);
If you want to add a new variable depending on the mode, just specify the key and value for that specific mode.
$modes: (
"&": (
"color": #000,
"bgc": #fff,
"bgc-contrast": #eee,
//...
),
"dark": (
"color": #fff,
"bgc": #000,
"bgc-contrast": #424242,
//...
),
);
To retrieve a variable, use the v($key)
function.
body {
color: v(color);
background-color: v(bgc);
}
div.contrasted {
background-color: v(bgc-contrast);
}
This will compile into:
body {
--color: #000;
--bgc: #fff;
--bgc-contrast: #eee;
}
body[dark] {
--color: #fff;
--bgc: #000;
--bgc-contrast: #424242;
}
body {
color: var(--color);
background-color: var(--bgc);
}
div.contrasted {
background-color: var(--bgc-contrast);
}
Note: It's not necessary to define every variable for each mode. If a variable is missing for a particular mode, it won't cause an error.
For example, this is perfectly acceptable:
$modes: (
"&": (
//...
),
"dark": (
"color": #fff,
"bgc": #000,
"bgc-contrast": #424242,
//...
);
//...
body {
color: v(color);
background-color: v(bgc);
}
div.contrasted {
background-color: v(bgc-contrast);
}
...will work without any issues.