css / csso

CSS minifier with structural optimizations
https://css.github.io/csso/csso.html
MIT License
3.76k stars 187 forks source link

Add support for CSS variable replacement #425

Open Jaeiya opened 3 years ago

Jaeiya commented 3 years ago

Before conversion

root: {
  --red: #ff0000;
}
.myclass { color: var(--red); }

After conversion

.myclass { color: #ff0000; }

I have a very large file with all the variables inside it for theme management; it would be nice to remove all those long names and just replace them with the colors. It would save a huge amount of space.

yawnoc commented 3 years ago

CSS variables (custom properties) can be inherited, so there are use cases where replacement is undesirable. E.g. if you define --colour-1, --colour-2, etc. in an external "theme" stylesheet, and then reference these variables in an embedded stylesheet.

There would need to be an option to disable variable replacement. Or even better, let the user supply a whitelist/blacklist of variable names that can/cannot be replaced.

dqh-au commented 1 year ago

It would also break situations when variables are used as runtime variables, for example overriding colours based on dark mode:

:root {
    --fg-color: black;
}
@media (prefers-color-scheme:dark) {
    :root {
        --fg-color: #dcdcdc;
    }
}

It's also possible to manipulate variable values from JavaScript. So I think if implemented this should be disabled by default.