如果文件丢失,如何使Gulp.src失败?

问题描述:

我们的gulp构建需要使用bower安装一堆库,然后将它们与我们分布在多个目录中的所有代码连接起来。这是它的样子:

Our gulp build takes a bunch of libraries installed with bower, then concatenates them with all the code we have distributed across several directories. Here's what it looks like:

  var jsFiles = [
    sourcePath + '/config/config.js',
    sourcePath + '/vendor/jquery/dist/jquery.js',
    sourcePath + '/vendor/js-cookie/src/js.cookie.js',
    sourcePath + '/vendor/modernizr/modernizr.js',
    sourcePath + '/vendor/lodash/lodash.js',
    sourcePath + '/vendor/picturefill/dist/picturefill.min.js',
    sourcePath + '/templates/**/*.js',
    sourcePath + '/pages/**/*.js'
  ],

gulp.task('build:js', ['jscs'], function() {
  return gulp.src(jsFiles)
  .pipe(concat('scripts.js'))
  .pipe(gulpif(isProd, uglify()))
  .pipe(gulp.dest(outputPath + '/webresources/js'));
});

我们的问题是,每当有人添加新库时,其他开发人员如果没有运行就会遇到问题 bower install 获取新组件。 scripts.js 在没有它们的情况下构建,因为它不会介意其中一个globs返回为空,即使它是一个命名文件。

Our problem is that whenever someone adds new libraries, other developers will encounter problems if they haven't run bower install to get the new components. The scripts.js gets built without them since it won't mind that one of the globs returns empty, even if it is a named file.

如何解决这个问题?如果glob返回零结果,有没有办法抛出错误?

How should this be solved? Is there a way to throw an error if a glob returns zero results?

因为似乎没有准备好解决方案,我写了一个模块来满足我们的需求。

Since there didn't seem to be a ready solution for this, I wrote a module to fit our needs.

files-exist 模块允许您检查数组中是否存在所有文件,如果缺少任何文件则抛出错误。它成功返回一个相同的数组,因此很容易就位。

The files-exist module allows you to check whether all files in an array are present, throwing an error if any are missing. It returns an identical array on success, so it is simple to drop in place.

  var jsFiles = [
    sourcePath + '/config/config.js',
    sourcePath + '/vendor/jquery/dist/jquery.js',
    sourcePath + '/vendor/js-cookie/src/js.cookie.js',
    sourcePath + '/vendor/modernizr/modernizr.js',
    sourcePath + '/vendor/lodash/lodash.js',
    sourcePath + '/vendor/picturefill/dist/picturefill.min.js',
    sourcePath + '/templates/**/*.js',
    sourcePath + '/pages/**/*.js'
  ],

filesExist = require('files-exist'),

gulp.task('build:js', ['jscs'], function() {
  return gulp.src(filesExist(jsFiles)) // Throws error if a file is missing
  .pipe(concat('scripts.js'))
  .pipe(gulpif(isProd, uglify()))
  .pipe(gulp.dest(outputPath + '/webresources/js'));
});