minify only some files

This commit is contained in:
Mylloon 2023-02-09 10:24:29 +01:00
parent 3ff2c60e58
commit c423780266
Signed by: Anri
GPG key ID: A82D63DFF8D1317F

View file

@ -27,24 +27,46 @@ async fn main() -> io::Result<()> {
println!("Listening to {}://{}:{}", config.scheme, addr.0, addr.1); println!("Listening to {}://{}:{}", config.scheme, addr.0, addr.1);
let static_folder = "static"; let static_folder = "static";
let dist_folder = "dist"; let dist_folder = format!("dist/{static_folder}");
// The static folder is minimized only in release mode // The static folder is minimized only in release mode
let folder = if cfg!(debug_assertions) { let folder = if cfg!(debug_assertions) {
format!("{static_folder}/") format!("{static_folder}/")
} else { } else {
let cfg = Cfg::new(); let cfg = Cfg::spec_compliant();
for entry in glob(&format!("{static_folder}/**/*.*")).unwrap() { for entry in glob(&format!("{static_folder}/**/*.*")).unwrap() {
let path = entry.unwrap(); let path = entry.unwrap();
let data = fs::read_to_string(&path).unwrap(); let path_with_dist = path.to_string_lossy().replace(static_folder, &dist_folder);
let minified = minify(data.as_bytes(), &cfg);
let path_with_dist = path.to_string_lossy().replace(static_folder, dist_folder); // Create folders
let new_path = Path::new(&path_with_dist); let new_path = Path::new(&path_with_dist);
fs::create_dir_all(new_path.parent().unwrap()).unwrap(); fs::create_dir_all(new_path.parent().unwrap()).unwrap();
let mut file = File::create(path_with_dist)?;
file.write_all(&minified)?; let mut copy = true;
if let Some(ext) = path.extension() {
// List of files who should be minified
if ["html", "css", "js", "svg", "webmanifest", "xml"]
.iter()
.any(|item| ext.to_string_lossy().to_lowercase().contains(item))
{
// We won't copy, we'll minify
copy = false;
// Minify
let data = fs::read(&path).unwrap();
let minified = minify(&data, &cfg);
// Write files
let mut file = File::create(&path_with_dist)?;
file.write_all(&minified)?;
}
}
if copy {
// If no minification is needed
fs::copy(path, path_with_dist)?;
}
} }
format!("{dist_folder}/") format!("{dist_folder}/")