iconsPlugin.mjs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { 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 name = basename(filepath).split('.')[0]
  31. const symbol = await compiler.addSymbol({
  32. id: `icon-${name}`,
  33. content: svgContent,
  34. path: filepath,
  35. })
  36. return {
  37. code: `export default \`${symbol.render()}\``,
  38. }
  39. }
  40. },
  41. })