parcel-bundler / lightningcss

An extremely fast CSS parser, transformer, bundler, and minifier written in Rust.
https://lightningcss.dev
Mozilla Public License 2.0
6.45k stars 186 forks source link

css variable declaration calc minification #506

Open MoritzLoewenstein opened 1 year ago

MoritzLoewenstein commented 1 year ago

Currently, the following calc expression will not be minified:

:root {
    --foo: calc(10px + 20px);
}

I know that it would break js code that relies on the computed style value for that property.

I will consider trying to implement this if there is a chance that it will get merged (as an opt-in option), otherwise feel free to close :)

devongovett commented 1 year ago

It is sorta hard if there are any unknown parameters like variables in there (e.g. calc(10px + var(--foo))). Even simplifying things like calc(10px + 20px + var(--bar)) might be challenging to do right. But for simple cases like the one you posted where all terms are known it could be done. If you're interested in contributing that, you could start in here and add a new handler for "calc" functions: https://github.com/parcel-bundler/lightningcss/blob/1203368b722ef0c9dffb03e70245423e352f6cff/src/properties/custom.rs#L380

From there, it would need to try parsing each possible type that supports calc, e.g. lengths, angles, times, etc. similar to this: https://github.com/parcel-bundler/lightningcss/blob/1203368b722ef0c9dffb03e70245423e352f6cff/src/properties/custom.rs#L460-L470

The difference would be using Length instead of LengthValue since Length supports calc but LengthValue does not. Then the result would just be a simplified value that could be stored as a TokenOrValue::Length etc.

Let me know if you have questions!

MoritzLoewenstein commented 1 year ago

Thanks for the explanation, started the implementation in #526. I will let you know when its ready or if I have questions!