img
Will & Skill logotype
Nyheter

2020-04-21

Using ES6 with AngularJS and gulp

Code on screen

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”: {
		[
			“env”,
			{
				“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:

Javascriptvar 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.

Javascriptvar es6 = [
	‘!client/app/dir/file.js’, // excluded
	...
	‘client/app/**/*.js’,
]

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

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

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:

Javascriptvar includes = [
	‘lib/bower_components/angular/angular.min.js’,
	‘assets/es6/js/**/*.js’, // include the newly transpiled code
]

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

Javascriptgulp.task(‘js’, [‘compile’], function () {
	return gulp.src(includes)
		.pipe(concat(‘app.js’))
		.pipe(gulp.dest(‘assets.js’));
});

Done!