Search code examples
csssassgulp

Gulp SCSS Color Variables to css


I have a scss file with over 20 lines of color variables. I want to create a css file with these variables to have one class for color and class for background-color.

Example:

from scss variable

$color-red: #FF0000;

to css

.color-red { color:#FF0000; }
.bg-color-red { background-color:#FF0000; }

Is there any Gulp plugin that allows me to do it? any recomendation accepted but i need to do it with gulp if it is possible.


Solution

  • As @chriskirknielsen suggested, sass maps and the @each rule is a good choice here. This is the first time I have used these concepts but this works in my testing.

    Your colors.scss file would look like this:

    $colors: ("color-red": "#FF0000", "color-green": "#00ff40");  // etc.
    
    @each $color, $value in $colors {
      .#{$color} {
        color: #{$value};
      }
      .bg-#{$color} {
        background-color: #{$value};
      }
    }
    

    The gulp-sass output in colors.css is:

    .color-red {
      color: #FF0000; }
    
    .bg-color-red {
      background-color: #FF0000; }
    
    .color-green {
      color: #00ff40; }
    
    .bg-color-green {
      background-color: #00ff40; }
    

    See https://sass-lang.com/documentation/values/maps#do-something-for-every-pair