2014-02-25 25 views
0

我有一个Gulp任务,它呈现一个包含Lodash模板的文件并将其放入我的构建目录中。我使用gulp-template来进行渲染。如何正确读取Gulp任务中的多个文件?

为了正确渲染,我的模板需要从我的构建目录传递一个文件列表。我使用glob得到这个列表。由于glob API是异步的,我不得不这样写我的任务:

gulp.task('render', function() { 
    glob('src/**/*.js', function (err, appJsFiles) { 

     // Get rid of the first path component. 
     appJsFiles = _.map(appJsFiles, function(f) { 
      return f.slice(6); 
     }); 

     // Render the file. 
     gulp.src('src/template.html') 
      .pipe(template({ 
       scripts: appJsFiles, 
       styles: ['style1.css', 'style2.css', 'style3.css'] 
      })) 
      .pipe(gulp.dest(config.build_dir)); 
    }); 
}); 

这对我来说似乎不雅。有没有更好的方式来写这个任务?

回答

2

解决您的特定问题的最简单方法是使用链接到的文档中的synchronous mode for glob。然后返回gulp.src的结果。

gulp.task('render', function() { 
    var appJsFiles = _.map(glob.sync('src/**/*.js'), function(f) { 
     return f.slice(6); 
    }); 
    // Render the file. 
    return gulp.src('src/template.html') 
     .pipe(template({ 
      scripts: appJsFiles, 
      styles: ['style1.css', 'style2.css', 'style3.css'] 
     })) 
     .pipe(gulp.dest(config.build_dir)); 
}); 
+0

我不知道glob有一个同步模式。这应该教我RTFM:/ –

0

如果您想让任务异步运行,请参加回调。

gulp.task('render', function(cb) { 
    glob('src/**/*.js', function (err, appJsFiles) { 
     if (err) { 
      return cb(err); 
     } 

     // Get rid of the first path component. 
     appJsFiles = _.map(appJsFiles, function(f) { 
      return f.slice(6); 
     }); 

     // Render the file. 
     gulp.src('src/template.html') 
      .pipe(template({ 
       scripts: appJsFiles, 
       styles: ['style1.css', 'style2.css', 'style3.css'] 
      })) 
      .pipe(gulp.dest(config.build_dir)) 
      .on('end', cb); 
    }); 
}); 
+0

这个'cb()'不会退出吞咽 – chovy

+0

现在就试试吧,错过了gulp.src流。 – robrich

+0

我不想做'gulp.src'。我需要我自己的带有元数据的文件对象列表。这不可能吗? – chovy

相关问题