index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env node
  2. import fs from 'fs-extra';
  3. import { optimize } from 'svgo';
  4. import svgstore from 'svgstore';
  5. export default function symbol(options = {}) {
  6. const { inFile = 'src/assets/svgs', outFile = 'public/fonts', fileName = 'symbol', ...rest } = options;
  7. // 如果 outFile 不存在, 则创建
  8. // If outFile does not exist, create it
  9. if (!fs.existsSync(outFile)) {
  10. fs.mkdirSync(outFile);
  11. }
  12. // 创建一个空的 svgstore
  13. // Create an empty svgstore
  14. const sprites = svgstore({ cleanDefs: true });
  15. // 循环 icons 目录下的所有 svg 文件
  16. // Loop through all svg files in the icons directory
  17. const svgs = fs.readdirSync(inFile);
  18. svgs.forEach(svg => {
  19. // 读取 svg 文件内容, 作为字符串
  20. // Read the svg file content as a string
  21. const code = fs.readFileSync(`${inFile}/${svg}`, 'utf8');
  22. // 使用 SVGO 进行优化
  23. // Use SVGO for optimization
  24. const result = optimize(code);
  25. // 删除 result 中的 fill p-id width height class 等属性
  26. // Delete fill p-id width height class and other attributes in result
  27. result.data = result.data
  28. .replace(/fill="[^"]*"/g, '')
  29. .replace(/p-id="[^"]*"/g, '')
  30. .replace(/width="[^"]*"/g, '')
  31. .replace(/height="[^"]*"/g, '')
  32. .replace(/class="[^"]*"/g, '');
  33. // 将优化后的 svg 添加到 sprites 中
  34. // Add the optimized svg to sprites
  35. sprites.toString({ inline: true });
  36. sprites.add(svg.replace('.svg', ''), result.data);
  37. });
  38. // 删除 sprites 的 <?xml...?> 标签和 <!DOCTYPE...> 标签 和 <defs/> 标签
  39. // Delete the <?xml...?> tag and <!DOCTYPE...> tag of sprites
  40. const spritesStr = sprites
  41. .toString()
  42. .replace(/<\?xml[^>]*>/g, '')
  43. .replace(/<!DOCTYPE[^>]*>/g, '')
  44. .replace(/<defs\/>/g, '');
  45. // 写入到指定的文件中
  46. // Write to the specified file
  47. fs.writeFileSync(outFile + '/' + fileName + '.svg', spritesStr);
  48. return {
  49. name: 'rollup-plugin-stdf-icon',
  50. };
  51. }