Tech BlogBrand Name

Using ES6 with AngularJS and gulp

To use ES6 code in your AngularJS project along with gulp you’re going to need to transpile the ES6 code into ES5 code using babel.

First, install the necessary packages: npm install babel-core babel-preset-env gulp-babel

In your package.json, after dependencies and devDependencies, add

"babel”: {
	“presets”: {
				“modules”: false

Your gulpfile.js also needs to be renamed to gulpfile.babel.js, to instruct gulp to use Babel.

First, include gulp-babel in your gulpfile.babel.js as such:

var gulp = require('gulp'),
	babel = require('gulp-babel')

You’ll want to break out the files that you want to transpile - probably just your own project and not angular itself - so we define what we want to transpile in a variable, where we can also exclude certain files if we don’t wish to transpile them.

var es6 = [
	‘!client/app/dir/file.js’, // excluded

Then we define the task to transpile the files and pipe them to where we want them to be:

gulp.task(‘transpile’, ['templates'], function () {
    return gulp.src(es6)
        .pipe(babel({ presets: ['env'] }))

When the transpilation is complete we can use the resulting files like we would normally, concatenating the project into a single app.js file. First define what we want to concatenate, for instance:

var includes = [
	‘assets/es6/js/**/*.js’, // include the newly transpiled code

And finally we define the task to build our app.js file:

gulp.task(‘js’, [‘compile’], function () {
	return gulp.src(includes)