Flatten glob down to one directory

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?

Problem courtesy of: Mark

Solution

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

Solution courtesy of: Mangled Deutz

Discussion

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));
});

Discussion courtesy of: daviestar

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'));
});

Discussion courtesy of: Corban Brook

This recipe can be found in it's original form on Stack Over Flow .

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章