Gulp Flatten

Posted by ryansouthgate on 20 Jul 2015

Whilst working on a personal project (more of that to follow), I’ve wanted to ensure all the different angularJS files go into the same directory after a build. i.e. I don’t want a folder each for angular.js, angular-resource.js etc

By default, gulp.dest(“dest path here”) overwrites all files in the path with the files from the gulp.src(“source path here”).

For the following folder structure

├── angular
│   ├── angular.js
│   ├── angular.min.js
├── angular-resource
│   ├── angular-resource.js
│   ├── angular-resource.min.js

This gulp code

gulp.src('angular*/**/angular*.js')
    .pipe(gulp.dest('lib/angular'));
});

Will result in this output structure…

├── angular-resource
│   ├── angular-resource.js
│   ├── angular-resource.min.js

What’s happened here is gulp did actually copy the “angular” js files over (min.js and js), however when it comes to do the “angular-resource” javascript files, it overwrites everything currently in the “angular” (output) folder. So that approach is not going to work.

Step in gulp-flatten

gulp-flatten does exactly what we need, it ensures that it only adds files to the specified output folder and existing files don’t get overwritten.

So for the initial folder structure above. The gulp code

var gulp = require("gulp"),
    // Don't forget to "require" gulp-flatten, I've got it from npmjs.com
flatten = require("gulp-flatten");

gulp.task("build", [], function () {
	        // Flatten angular paths
		gulp.src('angular*/**/angular*.js')
			// Do the flatten magic!
			.pipe(flatten())
			// output them in the lib/angular path
			.pipe(gulp.dest('lib/angular'));
};

Gives us this output structure

angular
│   ├── angular.js
│   ├── angular.min.js
│   ├── angular-resource.js
│   ├── angular-resource.min.js

Lovely jubbly!



comments powered by Disqus