Skip to content

Commit

Permalink
refactor: switch css minification to lighteningcss
Browse files Browse the repository at this point in the history
lighteningcss already got pulled in through a minify-html upgrade. So
we now to have use that pinned version anyway, and we can go ahead,
dropping css-minify.
  • Loading branch information
ctron committed Feb 2, 2024
1 parent 134f190 commit 44150d4
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 54 deletions.
46 changes: 4 additions & 42 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ cargo-lock = "9"
cargo_metadata = "0.18.1"
clap = { version = "4", features = ["derive", "env"] }
console = "0.15"
css-minify = "0.3"
directories = "5"
dunce = "1"
envy = "0.4"
Expand Down Expand Up @@ -76,7 +75,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
which = "5"
zip = "0.6"

# pin lightningcss, pulled in by minify-html
# pin lightningcss, used by trunk, also pulled in by minify-html
lightningcss = "=1.0.0-alpha.51"

[dev-dependencies]
Expand Down
37 changes: 27 additions & 10 deletions src/processing/minify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,35 @@ pub fn minify_js(bytes: Vec<u8>, mode: TopLevelMode) -> Vec<u8> {

/// perform CSS minification
pub fn minify_css(bytes: Vec<u8>) -> Vec<u8> {
use css_minify::optimizations::*;

if let Ok(css) = std::str::from_utf8(&bytes) {
match Minifier::default().minify(css, Level::One) {
Ok(result) => return result.into_bytes(),
Err(err) => {
tracing::warn!("Failed to minify CSS: {err}");
}
}
use lightningcss::stylesheet::*;

/// wrap CSS minification to isolate borrowing the original content
fn minify(css: &str) -> Result<String, ()> {
// parse CSS

let mut css = StyleSheet::parse(css, ParserOptions::default()).map_err(|err| {
tracing::warn!("CSS parsing failed, skipping: {err}");
})?;

css.minify(MinifyOptions::default()).map_err(|err| {
tracing::warn!("CSS minification failed, skipping: {err}");
})?;

Ok(css
.to_css(PrinterOptions {
minify: true,
..Default::default()
})
.map_err(|err| {
tracing::warn!("CSS generation failed, skipping: {err}");
})?
.code)
}

bytes
match std::str::from_utf8(&bytes) {
Ok(css) => minify(css).map(String::into_bytes).unwrap_or(bytes),
Err(_) => bytes,
}
}

/// perform HTML minification
Expand Down

0 comments on commit 44150d4

Please sign in to comment.