Slava Fomin II
Slava Fomin II

Reputation: 28661

Export variables from SASS to vanilla CSS?

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.

Upvotes: 4

Views: 1129

Answers (2)

Umbo
Umbo

Reputation: 3142

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

Upvotes: 3

Gavin Thomas
Gavin Thomas

Reputation: 1206

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

Upvotes: 2

Related Questions