您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

optimize-assets.mjs 1.2KB

123456789101112131415161718192021222324252627282930313233
  1. import fs from "node:fs/promises";
  2. import path from "node:path";
  3. import sharp from "sharp";
  4. const dir = new URL("../public/images/", import.meta.url);
  5. const files = (await fs.readdir(dir)).filter((f) =>
  6. /\.(png|webp|jpg)$/i.test(f) && !f.endsWith('-600.webp'),
  7. );
  8. let before = 0,
  9. after = 0;
  10. for (const file of files) {
  11. const src = new URL(file, dir);
  12. const input = await fs.readFile(src);
  13. before += input.length;
  14. const max = file.startsWith('logo.') ? 350 : 1400;
  15. const full = await sharp(input)
  16. .resize(max, max, { fit: "inside", withoutEnlargement: true })
  17. .webp({ quality: 83 })
  18. .toBuffer();
  19. const base = path.parse(file).name;
  20. await fs.writeFile(new URL(base + ".webp", dir), full);
  21. after += full.length;
  22. if (!["favicon", "logo"].includes(base)) {
  23. const small = await sharp(input)
  24. .resize(600, 600, { fit: "inside", withoutEnlargement: true })
  25. .webp({ quality: 80 })
  26. .toBuffer();
  27. await fs.writeFile(new URL(base + "-600.webp", dir), small);
  28. }
  29. if (file !== base + ".webp") await fs.unlink(src);
  30. }
  31. console.log(
  32. `Full images: ${(before / 1e6).toFixed(1)} MB → ${(after / 1e6).toFixed(1)} MB. Also generated responsive 600px images.`,
  33. );