img.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import fs from "fs";
  2. import path from "path";
  3. import sharp from "sharp";
  4. import { optimize as svgo } from "svgo";
  5. /**
  6. * @typedef {object} Src2Dest - Mapping of src to dest
  7. * @property {string} src - Name of the source file.
  8. * @property {string} dest - Name of the destination file.
  9. */
  10. /**
  11. * Convert a list of SVG files to PNG.
  12. *
  13. * @param {Src2Dest[]} items - Array of SVG files (src: SVG, dest:PNG) to convert.
  14. */
  15. async function svg2png(items) {
  16. items.forEach(async (item) => {
  17. try {
  18. fs.mkdir(path.dirname(item.dest), { recursive: true }, (err) => {
  19. if (err) throw err;
  20. });
  21. const info = await sharp(item.src)
  22. .png({
  23. force: true,
  24. compressionLevel: 9,
  25. palette: true
  26. })
  27. .toFile(item.dest);
  28. console.log(`[svg2png] created ${item.dest} -- bytes: ${info.size}, w:${info.width}px, h:${info.height}px`);
  29. } catch (err) {
  30. console.error(`ERROR: ${item.dest} -- ${err}`);
  31. throw err;
  32. }
  33. });
  34. }
  35. /**
  36. * Optimize SVG images for WEB.
  37. *
  38. * @param {import('svgo').Config} svgo_opts - Options passed to svgo.
  39. * @param {Src2Dest[]} items - Array of SVG files (src:SVG, dest:SVG) to optimize.
  40. */
  41. async function svg2svg(svgo_opts, items) {
  42. items.forEach(async (item) => {
  43. try {
  44. fs.mkdir(path.dirname(item.dest), { recursive: true }, (err) => {
  45. if (err) throw err;
  46. });
  47. const raw = fs.readFileSync(item.src, "utf8");
  48. const opt = svgo(raw, svgo_opts);
  49. fs.writeFileSync(item.dest, opt.data);
  50. console.log(`[svg2svg] optimized: ${item.dest} -- src: ${item.src}`);
  51. } catch (err) {
  52. console.error(`ERROR: optimize src: ${item.src} -- ${err}`);
  53. throw err;
  54. }
  55. });
  56. }
  57. export { svg2png, svg2svg };