'How to use js variable in scss?

In vite project, I defined an env variable in .env:

VITE_THEME=1

And I have a variables.scss file to define a variable:

$theme-color: red;

I can use import.meta.env.VITE_THEME to get VITE_THEME in js, but now I want to use it in variables.scss to change the theme-color like:

$theme-color: import.meta.env.VITE_THEME == 1 ? red : yellow;

How can I do this?



Solution 1:[1]

In this case, you should use a CSS-in-JS library. CSS is not a programming language, and you shouldn't just fetch some data with it. Alternatively, you can conditionally add a class to the body tag in JS and configure styles in CSS depending on that. There are ways to compile your SCSS so that it gets some data from a file, but it won't be reactive. If you want to only change an element, you could just conditionally apply classes with the style attribute too.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tagvi