5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

gulpで複数のファイルコピーを同期的に行う

Last updated at Posted at 2017-01-09

gulpでファイルをコピーするときに

gulp.task('copyFiles', () => {
    gulp.src('./src/a/**').pipe(gulp.dest("./dist"));
    gulp.src('./src/b/**').pipe(gulp.dest("./dist"));
    gulp.src('./src/c/**').pipe(gulp.dest("./dist"));
});

gulp.task('replace', ['copyFiles'], (){
    gulp.src('./src/a/index.html')
        .pipe(replace(/hoge/g, 'piyo'))
        .pipe(gulp.dest('./dist/a'));
});

みたいにやると、非同期的にコピーされてしまい、しかもcopyFilesが終わる前にreplaceが走ってしまい思った結果になりません。コピーが一つだけなら

gulp.task('copyFiles', () => {
    return gulp.src('./src/a/**').pipe(gulp.dest("./dist"));
});

gulp.task('copyFiles', (cb) => {
    gulp.src('./src/a/**').pipe(gulp.dest("./dist")).on('end'()=>{cb();});
});

のように出来ますが、複数のコピーを全部taskにしてつなげるのは流石に・・・・
で、gulpで同期的に何かをする方法は色々ありますが、generatorを使ってやってみたらこんな感じかなと。

gulp.task('copyFiles', (cb) => {
    var g = (function *(){
        yield gulp.src('./src/a/**').pipe(gulp.dest("./dist")).on('end',()=>{g.next();});
        yield gulp.src('./src/b/**').pipe(gulp.dest("./dist")).on('end',()=>{g.next();});
        yield gulp.src('./src/c/**').pipe(gulp.dest("./dist")).on('end',()=>{g.next();});
        yield cb();
    })();
    g.next();
});

gulp.task('replace', ['copyFiles'], (){
    gulp.src('./src/a/index.html')
        .pipe(replace(/hoge/g, 'piyo'))
        .pipe(gulp.dest('./dist/a'));
});

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?