iconsPlugin.mjs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { dirname, basename } from 'node:path'
  3. import { optimize } from 'svgo'
  4. import SVGCompiler from 'svg-baker'
  5. import { readFileSync } from 'node:fs'
  6. /**
  7. * @param {string} filepath
  8. * @returns {string}
  9. */
  10. const optimizeSvg = (filepath) => {
  11. // eslint-disable-next-line security/detect-non-literal-fs-filename
  12. const content = readFileSync(filepath, 'utf-8')
  13. const result = optimize(content, {
  14. plugins: [{ name: 'preset-default' }],
  15. })
  16. return result.data || content
  17. }
  18. export default () => ({
  19. name: 'zammad-plugin-svgo',
  20. enforce: 'pre',
  21. /**
  22. * @param {string} id
  23. * @returns {{code: string}}
  24. */
  25. async load(id) {
  26. if (id.endsWith('.svg?symbol')) {
  27. const filepath = id.replace(/\?.*$/, '')
  28. const svgContent = optimizeSvg(filepath)
  29. const compiler = new SVGCompiler()
  30. const dir = basename(dirname(filepath))
  31. const name = basename(filepath).split('.')[0]
  32. const symbol = await compiler.addSymbol({
  33. id: `icon-${dir}-${name}`,
  34. content: svgContent,
  35. path: filepath,
  36. })
  37. return {
  38. code: `export default \`${symbol.render()}\``,
  39. }
  40. }
  41. },
  42. })