svg元素颜色跟随style

25 阅读1分钟
  1. svg 设置属性 fill 为 currentColor
  2. path 不设置属性 fill
  • 正确
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
  <path d="M13 7H3v1h10V7z" />
</svg>
  • 错误
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16">
  <path fill="#546174" d="M13 7H3v1h10V7z" />
</svg>
  • 脚本
const fs = require('fs');
const path = require('path');
const { cwd } = require('process');

// 定义svg资源文件路径
const iconPath = path.join(cwd(), 'src/svgs');

const parseSVG = (iconPath) => {
  const iconFolders = fs.readdirSync(iconPath);

  for (const iconFolder of iconFolders) {
    const iconDir = path.join(iconPath, iconFolder);
    if (fs.statSync(iconDir).isDirectory()) {
      parseSVG(iconDir);
      continue;
    }
    // 仅处理.svg 文件
    if (path.extname(iconDir) !== '.svg') continue;
    let iconData = fs.readFileSync(iconDir, 'utf8');
    iconData = iconData.replace(/ fill="#([\da-fA-F]{3,6})"/g, '');
    iconData = iconData.replace('fill="none"', 'fill="currentColor"');
    fs.writeFileSync(iconDir, iconData);
  }
};
parseSVG(iconPath);