Crate const_css_minify

source ·
Expand description

github crates.io docs.rs

Include a minified css file as an inline const in your high-performance compiled web application.

You can call it with a path to your source css file, just like you might use the built-in macro include_str!():

use const_css_minify::minify;

// this is probably the pattern you want to use
const CSS: &str = minify!("./path/to/style.css");

IMPORTANT! the current version of const_css_minify resolves paths relative to the crate root (i.e. the directory where your Cargo.toml is). This behaviour is DIFFERENT from the rust built-in macros like include_str!() which use a path relative to the source file from which it’s invoked. Consider the current behaviour unstable and likely to change - our preference would be to match the established convention, but implementing this change is dependant on the stabilisation of a source path api in proc_macro as per https://github.com/rust-lang/rust/issues/54725

It’s also possible to include a raw string with your css directly in your rust source:

use const_css_minify::minify;

const CSS: &str = minify!(r#"
    input[type="radio"]:checked, .button:hover {
        color: rgb(100%, 100%, 100%);
        margin: 10px 10px;
    }
"#);
assert_eq!(CSS, "input[type=\"radio\"]:checked,.button:hover{color:#fff;margin:10px 10px}");

Note also that the current version of const_css_minify does not support passing in a variable. only the above two patterns of a path to an external file or a literal str will work.

const_css_minify is not a good solution if your css changes out-of-step with your binary, as you will not be able to change the css without recompiling your application.

§const_css_minify will:
  • remove unneeded whitespace and linebreaks
  • remove comments
  • remove unneeded trailing semicolon in each declaration block
  • opportunistically minify literal hex colors if and only if they can be expressed identically with a 3 character code (e.g. #ffffff will be substituted with #fff but #fffffe and #ffffffff will be left untouched)
  • minify colors specified by rgb function (e.g. rgb(255, 255, 254) will be substituted with #fffffe, and rgb(255, 255, 255) with #fff)
  • silently ignore any actual css syntax errors originating in your source file, and in so doing possibly elicit slightly different failure modes from renderers by altering the placement of whitespace around misplaced operators.
§const_css_minify will not:
  • compress your css using gz, br or deflate
  • change the semantic meaning of your semantically valid css
  • make any substitutions other than identical literal colors
  • do anything at all to alert you to invalid css - it’s not truly parsing the css, just scanning for and removing characters it identifies as unnecessary.

Macros§

  • Produce a minified css file as an inline const