Export variables from SASS to vanilla CSS?

十年热恋 提交于 2021-02-10 12:26:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!