Search code examples
cssangularsasswebpackcss-variables

Ways to define CSS variables from JSON file or from typescript files?


I want to define CSS variables like in Sass. Something like:

.someClass {
  background-image: $imageLink;
  color: $someColor;
}

And i Want to define $imageLink and $someColor in my class or in json file.

Can i do this without Sass or Less? (Or without css variables, because it does not supported in IE.)

I an using angular2 and webpack in my project.


Solution

  • Of course you cannot set SASS variables at run-time, because by that time the SASS has already been compiled.

    A classic approach is to instead think in terms of "themes", and select a theme by a class on a higher-level element (such as body). So you could have

    .darktheme  .someClass { color: white; }
    .lighttheme .someClass { color: black; }
    

    Now from your JS you can change the theme with

    document.body.classList.add('darktheme');