简体   繁体   中英

gulp-uglifyjs error when gulp.src returns no files

I have a unknown number of folders inside a directory called app that I am looping through to create a folderName.min.js for each.

Gulp script:

var es = require('event-stream');
var uglify = require('gulp-uglifyjs');
var fs = require('fs');
var path = require('path');

function getFolders(dir) {
  return fs.readdirSync(dir)
    .filter(function (file) {
      return fs.statSync(path.join(dir, file)).isDirectory();
  })
}

gulp.task('js', function () {
  var folders = getFolders('./src/app/');

  var streams = folders.map(function (folder) {

    return gulp.src(folder + '**/*.js')
      .pipe(uglify(folder + '.min.js', {
        mangle: true
      }))
      .pipe(gulp.dest('./dist/js'))
  });

  return es.concat.apply(null, streams);
});

The problem I am running in to is that not every folder contains *.js files. When gulp-uglifyjs encounters this case, I get

gulp-uglifyjs - No files given; aborting minification

and the stream aborts and all subsequent tasks do not get run. Am I able to

a) tell uglifyjs to proceed anyway if it runs in to this case

b) skip the task if gulp.src returned no files?

The solution was to modify my getFolders function to only return folders that contained JavaScript files. I did this by walking each subdirectory inside app and checking if any *.js files were found.

function getJSFolders(dir) {
  return fs.readdirSync(dir)
    .filter(function (file) {
      var files;
      var isDir = fs.statSync(path.join(dir, file)).isDirectory();
      var hasJs = false;

      if (isDir) {
        files = getFiles(path.join(dir, file));

        for (var i = 0; i < files.length; i++) {
          if (path.extname(files[i]) === '.js') {
            hasJs = true;
            break;
          }
        }
      }

      return isDir && hasJs;
    });
}

function getFiles(dir, filesArr) {
  var files = fs.readdirSync(dir);
  filesArr = filesArr || [];

  for (var i in files) {
    if (!files.hasOwnProperty(i)) continue;
    var name = dir + '/' + files[i];
    if (fs.statSync(name).isDirectory()) {
      getFiles(name, filesArr);
    } else {
      filesArr.push(name);
    }
  }

  return filesArr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM