MyFantasy512
MyFantasy512

Reputation: 688

How do I export a Sass variable to Javascript?

I have an Sass setup in my application that provides some custom properties as well as Sass $variables.

:root { --my-variable: #FFFFFF; }

$my-variable: var(--my-variable) !default;

And I would love to export those variables to Js using the :export tag, so that I can present them in the storybook.

For example:

:export {
  myVar: var(--my-variable)
  ...
}

But the only thing I was able to achieve, is that in Js I get the string literal, not the variable associated value, in this case #FFFFFF.

Do I need to do anything specific in my configuration to make this happen?

Upvotes: 0

Views: 311

Answers (1)

Simplicius
Simplicius

Reputation: 2095

This is due to the fact that only browsers can interpret custom properties. If custom property is declared like this:

:root { --body-backgroundColor: #fafafa; }

body { background-color: var(--body-backgroundColor); }

You can manipulate --body-backgroundColor: via Js, however Sass will interpret your $my-variable: var(--my-variable) !default; as a string, since it can't associate a custom property with its value.

The best practice here is to pass the variable inside the custom property.

$myVar: #fff !default;

:root { --my-var: #{$myVar}; }

body { background-color: var(--my-var); }

:export {
  myVar: $myVar;
  ...
}

Upvotes: 1

Related Questions