Home > Back-end >  How to use js variable in scss?
How to use js variable in scss?

Time:03-22

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?

CodePudding user response:

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.

CodePudding user response:

You can't do that. SASS is a CSS preprocessor, which means that all SASS specific information disapears when you compile it to CSS. You can create custom class and add an element with js.

  • Related