Setting up Babel with Gulp

So after initially using the WebStorm file watcher mechanism to transpile to ES5 using Babel, I decided to instead do it the “correct” way: using Gulp.  In this case my project is a Node/Express Rest Api, in which case I would end up using Gulp anyway for various other tasks.  Here’s the easy setup:

Add in the following dependencies using npm:

npm install gulp --save-dev
npm install gulp-babel --save-dev
npm install gulp-sourcemaps --save-dev
npm install require-dir --save-dev

My project structure is set up as:

  • src – The untranspiled source.
  • dist – The transpiled source.
  • build – The build files.  I typically put a paths file inside of build that has all of my project path information for conducting builds and add add a tasks directory under build for the actual build tasks.

We can now add a build.js file under build–>tasks which will look like:

var gulp = require("gulp");
var sourceMaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");

gulp.task("build", function () {
    return gulp.src("src/**/*.js") //get all js files under the src
        .pipe(sourceMaps.init()) //initialize source mapping
        .pipe(babel()) //transpile
        .pipe(sourceMaps.write(".")) //write source maps
        .pipe(gulp.dest("dist")); //pipe to the destination folder
});

Now define your main gulpfile.js in the root project directory.  It simply uses require-dir to require all files in the build/tasks folder (to pull in all tasks).

require('require-dir')('build/tasks');

That’s it!  now run “gulp build” at the command prompt…all set.  This is obviously pretty bare-bones.  Normally I might also be using some other packages to set up gulp tasks that enhance my build process by:

  • Cleaning the dist directory pre-transpile (del)
  • Setting up a linter (jshint)
  • Running the project with change monitoring (gulp-nodemon)