img.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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(
  17. async (item) => {
  18. try {
  19. fs.mkdir(path.dirname(item.dest), { recursive: true }, (err) => {
  20. if (err)
  21. throw err;
  22. });
  23. const info = await sharp(item.src).png({
  24. force: true,
  25. compressionLevel: 9,
  26. palette: true,
  27. }).toFile(item.dest);
  28. console.log(
  29. `[svg2png] created ${item.dest} -- bytes: ${info.size}, w:${info.width}px, h:${info.height}px`
  30. );
  31. } catch (err) {
  32. console.error(`ERROR: ${item.dest} -- ${err}`);
  33. throw(err);
  34. }
  35. }
  36. );
  37. }
  38. /**
  39. * Optimize SVG images for WEB.
  40. *
  41. * @param {import('svgo').Config} svgo_opts - Options passed to svgo.
  42. * @param {Src2Dest[]} items - Array of SVG files (src:SVG, dest:SVG) to optimize.
  43. */
  44. async function svg2svg(svgo_opts, items) {
  45. items.forEach(
  46. async (item) => {
  47. try {
  48. fs.mkdir(path.dirname(item.dest), { recursive: true }, (err) => {
  49. if (err)
  50. throw err;
  51. });
  52. const raw = fs.readFileSync(item.src, "utf8");
  53. const opt = svgo(raw, svgo_opts);
  54. fs.writeFileSync(item.dest, opt.data);
  55. console.log(
  56. `[svg2svg] optimized: ${item.dest} -- src: ${item.src}`
  57. );
  58. } catch (err) {
  59. console.error(`ERROR: optimize src: ${item.src} -- ${err}`);
  60. throw(err);
  61. }
  62. }
  63. );
  64. }
  65. export { svg2png, svg2svg };