2

I am using Gulp to store multiple SVG files into SVG storages which are later reused in order to maximize performance. However, I am now using a rather interesting folder structure where the paths contain interchangeable fixed and dynamic parts.

Let me illustrate. Here is the folder structure I am using. The app/images/products folder contains folders named productA, productB etc. which again contain a subfolder called color-sprites full of SVG files ready to get combined into a single file and stored in build/images/products/{product name}/color-sprites.svg.

root/
    |_ gulpfile.js
    |_ app 
        |_ images
            |_ products
                |_ **productA**
                    |_ color-sprites
                        |_ sprite1.svg
                        |_ sprite2.svg
                        |_ ...
    |_ build
        |_ images
            |_ products
                |_ **productA**
                    |_ color-sprites.svg

Here is a simplified version of the code I am trying to use to accomplish what I need (take note that rename is an instance of gulp-rename).

gulp.task('svg-color-sprites', function () {
    return gulp.src('app/images/products/**/color-sprites/*.+(svg)')
        .pipe(svgMin())
        .pipe(svgStore())
        .pipe(rename(...))
        .pipe(gulp.dest('build/images/'));
});

The problem is that I am not exactly sure how to access current stream parameters in order to construct a target with gulp-rename because running the gulpfile.js like this results in taking the first parent element of the path before * or ** which again results in creating a file called products.svg in build/images/. I've seen a couple of examples which use path to access the basename, relative path etc. but I am not sure how to use it in the context of gulp streams.

4

1 回答 1

1

您现在做事的方式将为您的所有 SVG 创建一个组合 SVG,而不是为每个产品创建一个组合 SVG 。事实上,如果你有两个这样的文件:

productA/color-sprites/sprite1.png
productB/color-sprites/sprite1.png

整个事情都会失败,因为gulp-svgstore期望文件名是唯一的

您需要做的是每个产品都有一个 gulp 流,每个产品生成一个组合 SVG。

这意味着您需要遍历products文件夹中的所有目录,为每个目录初始化一个流,然后合并它们,以便您可以从任务中返回一个流。

获取products文件夹中所有目录的最简单方法是使用glob和合并流,使用merge-stream.

var glob = require('glob');
var merge = require('merge-stream');
var path = require('path');

gulp.task('svg-color-sprites', function () {
  return merge(glob.sync('app/images/products/*').map(function(productDir) {
    var product = path.basename(productDir);
    return gulp.src(productDir + '/color-sprites/*.+(svg)')
      .pipe(svgMin())
      .pipe(svgStore())
      .pipe(gulp.dest('build/images/products/' + product));
  }));
});

由于在基本文件夹之后gulp-svgstore自动命名生成的组合 SVG ,您甚至根本不需要使用。组合的 SVG 文件将自动命名为.gulp-renamecolor-sprites.svg

于 2016-09-24T07:24:38.600 回答