我用 Grunt 任务来做这件事。通过使用“grunt-text-replace”,我可以通过自定义正则表达式传递我的缩小 SVG(svgmin),该表达式将所有乱码的类引用替换为正确的类。
例如,在 Illustrator 中,将图层/对象名称声明为class="tree"。这将由 Illustrator 导出为id="class="tree""。下面的 grunt 任务将处理它并使其成为class="tree"。我还在其他一些将进行 ID 清理的子任务下方粘贴(推荐)。
    replace: {
        // ID cleanup: performs a manual ID cleanup as Illustrator exports a mess
        illustrator: {
            src: ['assets/svg/optimised/*.svg'],
            overwrite: true,
            replacements: [{
                // Remove escaped underscore character
                from: '_x5F_',
                to: '_'
            }, {
                // Replace class names with proper classes
                //class_x3D__x22_tank-option_x22__2_
                from: /id\=\"class_x3D__x22_(.+?)_x22_(.*?)\"/gi,
                to: function(matchedWord, index, fullText, regexMatches) {
                    return 'class="'+ regexMatches[0].toLowerCase()+'"';
                }
            }, {
                // Lowercase all ids
                from: /id\=\"(.+?)\"/gi,
                to: function(matchedWord, index, fullText, regexMatches) {
                    return 'id="'+ regexMatches[0].toLowerCase()+'"';
                }
            }, {
                // Lowercase all id references to match the previous replace rule
                from: /url\(\#(.+?)\)/gi,
                to: function(matchedWord, index, fullText, regexMatches) {
                    return 'url(#'+ regexMatches[0].toLowerCase() +')';
                }
            }, {
                // Lowercase all id href to match the previous replace rule
                from: /href\=\"\#(.+?)\"/gi,
                to: function(matchedWord, index, fullText, regexMatches) {
                    return 'href="#'+ regexMatches[0].toLowerCase() +'"';
                }
            }, {
                // Remove all font references as we will use CSS for this
                from: /font\-family\=\"(.+?)\"/gi,
                to: function(matchedWord, index, fullText, regexMatches) {
                    return '';
                }
            }]
        }
    }
然后你可以在你的 Gruntfile 中调用这个任务:
grunt.registerTask('svgclean', [
    'replace:illustrator'
]);