Babel for Beginners

Start writing in ES6 now!


What is Babel?

Babel is a JavaScript transpiler. What?. Trans as in transform and piler as in compiler. Therefore a transpiler coverts code from one format to another. Specifically Babel transforms your code from EcmaScript6 to EcmaScript5.

Why use Babel?

If you aren’t using bable to transpile your projects then you can’t write in ES6. There are lots of benefits to writing in ES6

Getting started

Navigate to a your projects root folder in the terminal then run the following command:

  npm install --save-dev babel-cli

This will:

  • Install the Gulp client globally
  • Install Gulp to the devDependencies for this project
  • Create a gulpfile.js (Used for configuring gulp.).

Then add the following to your gulpfile.js

'use strict';
var gulp = require('gulp');

gulp.task('default', function() {
  // place code for your default task here
});

Now you have everything setup! If you run gulp in the terminal in will run the default task, i.e the task we just created in the gulpfile. But nothing will happen because we haven’t actually told gulp what to do…

Gulp has a fantastic list of recipes. You may find exactly what you are already looking for in there!

I am going to use one of the recipes called ‘Output both a minified and non-minified version’

'use strict';

// require the necessary gulp modules
var gulp = require('gulp');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');

// Define the location of our build directory
var destination = 'build/';

gulp.task('default', function() {
  return gulp.src('foo.js')
    // This will output the non-minified version
    .pipe(gulp.dest(destination))
    // This will minify and rename to foo.min.js
    .pipe(uglify())
    .pipe(rename({ extname: '.min.js' }))
    .pipe(gulp.dest(destination));
});