问题
Consider I have a long list of SASS variables in different .scss
files like this:
$app-color-white: #ffffff;
$app-color-black: #000000;
What would be the most effective way to export these variables as vanilla CSS variables?
:root {
--app-color-white: #ffffff;
--app-color-black: #000000;
}
Maybe, there is a SASS-way or even some pre-processor?
I want my SASS framework to be also used in vanilla CSS projects.
回答1:
I think the best way to do this would be using something like a variable map;
E.g.
// sass variable map
$colors: (
primary: #FFBB00,
secondary: #0969A2
);
// ripped CSS4 vars out of color map
:root {
// each item in color map
@each $name, $color in $colors {
--color-#{$name}: $color;
}
}
Output:
:root {
--color-primary: #FFBB00;
--color-secondary: #0969A2;
}
Source: https://codepen.io/jakealbaugh/post/css4-variables-and-sass
回答2:
This is now possible thanks to sass modules and the new sass:meta.module-variables() function: it
Returns all the variables defined in a module, as a map from variable names (without $) to the values of those variables.
For example
// _vars.scss
$color: red;
$font: Helvetica, sans-serif;
// style.scss
@use 'sass:meta';
@use 'vars';
:root {
@each $name, $value in meta.module-variables(vars) {
--#{$name}: #{$value};
}
}
Outputs
:root {
--color: red;
--font: Helvetica, sans-serif;
}
⚠️ Sass modules are currently only supported in Dart Sass
来源:https://stackoverflow.com/questions/51785846/export-variables-from-sass-to-vanilla-css