X

Using ECMAScript 2015 (ES2015/ES6) with Gulp

Follow the below steps to use ECMAScript 2015 (formerly known as ECMAScript 6) while writing gulp file. Step 1: From gulp 3.9 version onwards we can use ECMAScript 2015, so make sure you installed the latest version of gulp into your project. Check the gulp version before proceeding, run the following command at root of…

Follow the below steps to use ECMAScript 2015 (formerly known as ECMAScript 6) while writing gulp file.

Step 1:

From gulp 3.9 version onwards we can use ECMAScript 2015, so make sure you installed the latest version of gulp into your project.

Check the gulp version before proceeding, run the following command at root of the project to check the currently installed gulp version.


$ gulp -v

Above command will print the locally installed, globally installed gulp version. If any of the versions are below 3.9, update them to latest version using following commands.


$ npm update gulp        #updates the local gulp package
$ npm update gulp  -g    #updates the global gulp package

Incase if you don’t have the gulp, run the following commands to install.


$ npm install gulp -g
$ npm install gulp --save-dev

Step 2:

We know today’s browsers doesn’t understand ES2015, so we need to use a transpiler like babel. Lets install babel into our project.


$ npm install babel-core babel-preset-es2015 --save-dev

Step 3:

We need to instruct the gulp to use babel. Create “.babelrc” config file in the project root, then add the following code.


{
  "presets": ["es2015"]
}

Step 4:

Generally we name our gulp file as “gulpfile.js“, but to rename it as “gulpfile.babel.js“.

We are now ready to use ES 2015 in gulp code.

Gulp file using ECMAScript 2015

We are now ready to use ES 2015 in gulp code. Here is a sample gulp file using ES2015 to convert sass files to css. First install gulp-sass package to use it with gulp:


$ npm install gulp-sass --save-dev

gulpfile.babel.js


'use strict';

import gulp from 'gulp';
import sass from 'gulp-sass';

gulp.task('sass', () => {
  return gulp.src('src/styles/*.scss')
             .pipe(sass().on('error', sass.logError))
             .pipe(gulp.dest('dist/styles/'));
});

Useful Links:

Categories: JAVASCRIPT
Shravan Kumar Kasagoni: