You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

generate-svg.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env node
  2. 'use strict';
  3. const fastGlob = require('fast-glob');
  4. const Svgo = require('svgo');
  5. const {resolve, parse} = require('path');
  6. const {readFile, writeFile, mkdir} = require('fs').promises;
  7. const glob = (pattern) => fastGlob.sync(pattern, {cwd: resolve(__dirname), absolute: true});
  8. const outputDir = resolve(__dirname, '../public/img/svg');
  9. function exit(err) {
  10. if (err) console.error(err);
  11. process.exit(err ? 1 : 0);
  12. }
  13. async function processFile(file, {prefix = ''} = {}) {
  14. let name = parse(file).name;
  15. if (prefix) name = `${prefix}-${name}`;
  16. if (prefix === 'octicon') name = name.replace(/-[0-9]+$/, ''); // chop of '-16' on octicons
  17. const svgo = new Svgo({
  18. plugins: [
  19. {removeXMLNS: true},
  20. {removeDimensions: true},
  21. {
  22. addClassesToSVGElement: {
  23. classNames: [
  24. 'svg',
  25. name,
  26. ],
  27. },
  28. },
  29. {
  30. addAttributesToSVGElement: {
  31. attributes: [
  32. {'width': '16'},
  33. {'height': '16'},
  34. {'aria-hidden': 'true'},
  35. ],
  36. },
  37. },
  38. ],
  39. });
  40. const {data} = await svgo.optimize(await readFile(file, 'utf8'));
  41. await writeFile(resolve(outputDir, `${name}.svg`), data);
  42. }
  43. async function main() {
  44. try {
  45. await mkdir(outputDir);
  46. } catch {}
  47. for (const file of glob('../node_modules/@primer/octicons/build/svg/*-16.svg')) {
  48. await processFile(file, {prefix: 'octicon'});
  49. }
  50. for (const file of glob('../web_src/svg/*.svg')) {
  51. await processFile(file);
  52. }
  53. }
  54. main().then(exit).catch(exit);