gulp-imagemin 正在将 SVG 文件缩小到 0kb

gulp-imagemin is minifying SVG file down to 0kb

我有一个 SVG 文件,其中包含几个代表图标的 <symbol> 标签。它看起来像这样:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
  <symbol id="icon-arrow_carrot_up_alt" viewBox="0 0 0 0">
    <path d="M544 1024c265.088 0 480-214.912 480-480s-214.912-480-480-480-480 214.912-480 480 214.912 480 480 480zM313.728 601.152l207.552-207.552c6.272-6.272 14.464-9.344 22.72-9.344s16.448 3.072 22.72 9.344l207.552 207.552c12.48 12.48 12.48 32.768 0 45.248s-32.768 12.48-45.248 0l-185.024-185.024-185.024 185.024c-12.48 12.48-32.768 12.48-45.248 0s-12.48-32.768 0-45.248z" fill="none"></path>
  </symbol>
  <symbol id="icon-arrow_carrot-2down" viewBox="0 0 0 0">
    <path d="M702.592 523.648l-191.744 169.6-191.744-169.6c-12.544-12.544-32.96-12.544-45.504 0s-12.544 32.96 0 45.504l214.080 189.376c6.4 6.4 14.784 9.472 23.168 9.344 8.384 0.128 16.768-2.88 23.168-9.28l214.080-189.376c12.544-12.544 12.544-32.96 0-45.504s-32.96-12.608-45.504-0.064zM748.096 294.144c-12.544-12.544-32.96-12.544-45.504 0l-191.744 169.6-191.744-169.6c-12.608-12.544-33.024-12.544-45.568 0s-12.544 32.96 0 45.504l214.080 189.376c6.4 6.4 14.784 9.472 23.168 9.344 8.384 0.128 16.832-2.944 23.168-9.344l214.080-189.376c12.672-12.544 12.672-32.896 0.064-45.504z" fill="none"></path>
  </symbol>
  ...
</svg>

我通过 gulp imagemin 任务 运行 这个文件,如下所示:

var gulp = require('gulp');
var changed = require('gulp-changed');
var imagemin = require('gulp-imagemin');

gulp.task('optimize-images', function() {
    return gulp.src(paths.img.src + '/**/*')
        .pipe(changed(paths.img.dest))
        .pipe(imagemin([
            imagemin.svgo({
                plugins: [
                    {removeViewBox: true},
                    {cleanupIDs: false}
                ]
            })
        ]))
        .pipe(gulp.dest(paths.img.dest));
});

文件被缩小并放在正确的目标目录中,但是它说它已经优化了 100% 的文件,并且它的大小下降到 0kb,没有文件内容。 SVG 已从文件中完全删除。

为什么这个 svg 的所有文件内容都被破坏了,我该如何修复?

Lol woops,我在 svgo/svgo 插件页面上发现 this issue gulp-imagemin 使用。注意到:

<symbol> is considered empty by itself, because it's not rendered. That's why it's being removed by default. You need to turn off removeUselessDefs as suggested above.

所以我在我的任务中添加了以下选项:

plugins: [
    {cleanupIDs: false},
    {removeUselessDefs: false},
    {removeViewBox: true},
]

还是不行,然后我意识到style="display: none;"<svg>标签上,这意味着它没有被渲染。 SVG 由 gulp-icomoon-builder 包自动生成,因此对其进行了解释。该包提供了一个选项来指定自定义外部模板来生成文件,因此我将创建一个没有内联显示样式的模板。

所以取消 display: none; 样式解决了这个问题。