Getting Started with ES6 (ES2015) and Babel

By  on  

If you don't do much work with Node.js there's a good chance you haven't explored the new syntax additions to the JavaScript language provided by ES2015.  These language additions include arrow functions, classes, block scoping, and more.  These language additions have slowly made their way to Chrome and Firefox so if you haven't taken the time to learn ES2015:  now is the time!  And what better way to do that than writing your JavaScript in ES2015 and using Babel to transpile it into "traditional" JavaScript for the browser?  Let me show you how to get started!

Step 1:  Install Babel with ES2015 Addon

Babel's CLI is available as a package from NPM so we'll start by installing it:

npm install babel-cli

Next we'll install the babel-preset-es2015 addon so we can use the new syntax additions:

npm install babel-preset-es2015

Babel has many addons for a variety of language modifications (like JSX) but this one addon is all we need to get started.

Step 2:  Create a .babelrc File

The small file allows us to create a preset for babel usage; since we only have the  babel-preset-es2015 addon, we'll only add that to the file:

echo '{ "presets": ["es2015"] }' > .babelrc

At this point we have Babel installed and preferences set!

Step 3:  Create Your JavaScript Files!

The fun part will be playing around with the new syntax!  Here's a very simple code snippet with arrow functions:

// Just playing around, this doesn't really do anything
((con) => {
  ['yes', 'no'].forEach((item) => {
    con.log(item);
  })
})(console);

The babel-preset-es2015 addon also supports JavaScript classes and more but let's keep our sample simple.  OK, sample is created, let's transpile it into "traditional" JavaScript for browsers that don't yet support ES2015!

Step 4:  Transpile the JavaScript

With Babel in place and our JavaScript code ready for treatment, we'll trigger the process:

./node_modules/.bin/babel src -d dest

That command transpiles every JavaScript file in the src directory and places it within the dest directory.  Our sample JavaScript file becomes:

'use strict';

(function (con) {
  ['yes', 'no'].forEach(function (item) {
    con.log(item);
  });
})(console);

You'll recognize that as something that you've been writing for years!

It's important to note that if you don't care about the browser you can simply run node myFile.js and ensure your code works properly (since current node is fitted with ES2015 syntactic sugar).  It's also important to point out that arrow functions were simply my example and that ES2015 has many, many more syntactical updates. Moreover the arrow function syntax changes the implications of binding so please study each type of syntactic update before using!

Take the time to play around with ES2015 -- it will be in all major browsers soon and should be quicker to type and more compact in size.  Once you start you'll look to use the new syntax everywhere!

Recent Features

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • By
    Fancy FAQs with jQuery Sliders

    Frequently asked questions can be super boring, right? They don't have to be! I've already shown you how to create fancy FAQs with MooTools -- here's how to create the same effect using jQuery. The HTML Simply a series of H3s and DIVs wrapper...

  • By
    CSS Selection Styling

    The goal of CSS is to allow styling of content and structure within a web page.  We all know that, right?  As CSS revisions arrive, we're provided more opportunity to control.  One of the little known styling option available within the browser is text selection styling.

Discussion

  1. You can try ES2015 directly in your browser with http://esnextb.in (https://github.com/voronianski/esnextbin). What’s good is it allows to import NPM modules directly in browser.

  2. Gaurang Tandon

    “./node_modules/.bin/babel src -d dest” looks a bit too long. I would just use gulp, takes five minutes to set up, but makes this task (and many others) pretty easy, especially, with its “default” task and “watch” files functionality.

    • I also use gulp but I don’t want to require it for this post ;)

  3. Daniel Latter

    Hi, I followed the article, but I get a TypeError:

    ["yes","no"].each is not a function

    It does transpile the arrow function correctly though, Am I missing something?

    • shabnam

      I got this error too

    • Sorry! It’s .forEach

  4. Noel

    I get an error: Plugin/Preset files are not allowed to export objects, only functions.
    my .babelrc:

    "presets": [
            "es2015",
            [
              "@babel/preset-env",
              {
                "modules": "commonjs",
                "targets": {
                  "node": "current"
                }
              }
            ]
          ]
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!