Flatten glob down to one directory

2019-01-18 02:33发布

问题:

Within Gulp, I am using gulp.src to select every font file from a directory:

gulp.task('copy-fonts', function() {
   gulp.src('components/**/*.{ttf,woff,eof,svg}')
   .pipe(gulp.dest('build/fonts'));
});

However, I would like to have all of these font files wind up in one directory side-by-side rather than have the entire tree re-created from the components directory.

Looking in the Gulp, Gulp Utils, and npm-glob APIs didn't really help me, though I could've easily skipped by it.

What would the best way to go about this?

回答1:

I would use gulp-flatten:

var flatten = require('gulp-flatten');
gulp.task('copy-fonts', function() {
  gulp.src('dependencies/**/*.{ttf,woff,eof,svg}')
  .pipe(flatten())
 .pipe(gulp.dest('build/fonts'));
});

As to how this is done internally, check: https://github.com/armed/gulp-flatten/blob/master/index.js



回答2:

Another option is to simply rewrite the file path inside gulp.dest:

var path = require('path');
gulp.task('copy-fonts', function() {
    return gulp.src('components/**/*.{ttf,woff,eof,svg}')
        .pipe(gulp.dest(function(file) {
            file.path = file.base + path.basename(file.path);
            return 'build/fonts';
        }));
});

You can also use this technique with gulp-changed:

var path = require('path');
var changed = require('gulp-changed');

gulp.task('copy-fonts', function() {
  var dest = 'build/fonts';
  return gulp.src('components/**/*.{ttf,woff,eof,svg}')
    .pipe(changed(function(file) {
      file.path = file.base + path.basename(file.path);
      return dest;
    }))
    .pipe(gulp.dest(dest));
});


回答3:

Another option is to use the glob library to unglob your paths, and then pass the file paths into gulp.src. When gulp src receives unglobbed file paths the relative dir is not maintained and simply copies the file to the root of the dest dir you specify. It can also be useful to unglob your paths first if you need to do any custom filtering or appending before setting src.

glob = require('glob');
gulp.task('copy-fonts', function() {
  files = glob.sync('dependencies/**/*.{ttf,woff,eof,svg}');

  gulp.src(files)
  .pipe(gulp.dest('build/fonts'));
});


标签: node.js gulp