2017年12月6日 星期三

[Gulp] Transpile ES6 to ES5 with gulp-babel

 gulp   gulp-babel   ES6/ES2015

              
Introduction


Here is a basic tutorial about how to use gulp-babel for transpiling javascript from ES6(2015) to ES5 to support legacy browsers.

Also we will use the additional plugin to

1.  Transpile the arrow function: ()=>{}
2.  Transpile built-in classes such as Date, Array, DOM …etc



Implement


Install

gulp-babel

$ npm install gulp-babel --save-dev


babel-plugin-transform-es2015-arrow-functions

$ npm install babel-plugin-transform-es2015-arrow-functions --save-dev


babel-plugin-transform-es2015-classes

$ npm install babel-plugin-transform-es2015-classes --save-dev




Usage

gulpfile.js

var gulp = require('gulp');
var babel = require("gulp-babel");


var root_path = {
    webroot: "./wwwroot/"
}

//babel transpile
gulp.task('babel-js', function () {
    return gulp.src([
        root_path.webroot + "/*.js"
    ])
    .pipe(babel())
    .pipe(rename({ suffix: '.compile' }))
    .pipe(gulp.dest(function (file) {
return file.base;
}));
});


//babel transpile with plugins
gulp.task('babel-js-plugin', function () {
    return gulp.src([
        root_path.webroot + "/*.js"
    ])
    .pipe(babel(
{ plugins: ["transform-es2015-arrow-functions", "transform-es2015-classes"]}
))
    .pipe(rename({ suffix: '.compile' }))
    .pipe(gulp.dest(function (file) {
return file.base;
}));
});





Reference







沒有留言:

張貼留言