Gulp可以覆盖所有src文件吗?
收藏

假设我要替换一堆文件中的版本号,其中许多文件位于子目录中。我将通过gulp-replace通过管道传输文件以运行regex-replace函数;但我最终还是要覆盖所有原始文件。

该任务可能看起来像这样:

gulp.src([
    './bower.json',
    './package.json',
    './docs/content/data.yml',
    /* ...and so on... */
  ])
  .pipe(replace(/* ...replacement... */))
  .pipe(gulp.dest(/* I DONT KNOW */);

So how can I end it so that each src file just overwrites itself, at its original location? Is there something I can pass to gulp.dest() that will do this?

最佳答案

我可以想到两种解决方案:

  1. Add an option for base to your gulp.src like so:

    gulp.src([...files...], {base: './'}).pipe(...)...
    

    This will tell gulp to preserve the entire relative path. Then pass './' into gulp.dest() to overwrite the original files. (Note: this is untested, you should make sure you have a backup in case it doesn't work.)

  2. Use functions. Gulp's just JavaScript, so you can do this:

    [...files...].forEach(function(file) {
        var path = require('path');
        gulp.src(file).pipe(rename(...)).pipe(gulp.dest(path.dirname(file)));
    }
    

    If you need to run these asynchronously, the first will be much easier, as you'll need to use something like event-stream.merge and map the streams into an array. It would look like

    var es = require('event-stream');
    
    ...
    
    var streams = [...files...].map(function(file) {
            // the same function from above, with a return
            return gulp.src(file) ...
        };
    return es.merge.apply(es, streams);
    

    公众号
    关注公众号订阅更多技术干货!