user3054986
user3054986

Reputation: 437

How to remove whitespaces from string literals in Rust during compile time?

Assuming I have multiline string nicely formatted in my source code:

let style_text = ".styled {
border: 0;
line-height: 3.5;
padding: 0 20px;"

I don't want to transmit unnecessary whitespace to the browser, but I also don't want to remove it for every request.

How can I remove all whitespace at compile time?

Upvotes: 1

Views: 1502

Answers (1)

Peter Hall
Peter Hall

Reputation: 58735

Macros are likely overkill for something like this, which would be the compile-time option.

Next best to compile-time is to just do it once.

lazy_static! {
    pub static ref STYLES: String = minify_styles(
        ".styled {
            border: 0;
            line-height: 3.5;
            padding: 0 20px;
        }"
    );
}

Now use STYLES instead of the literal string.

When implementing minify_styles, make sure to use a proper CSS minifier, rather than just stripping whitespace. Whitespace can be contextually significant in CSS, e.g. you don't want to turn padding: 0 20px into padding:020px.

Upvotes: 4

Related Questions