Lesson 2. Transpiling with Babel

When new features are added to JavaScript, the browsers always have to play a game of catch-up. It takes time after an update to JavaScript’s specification before all modern browsers have everything fully implemented and supported. In order to use all of the features covered in this book, you’ll make use of the technique covered in this lesson: transpiling.

2.1. What is transpiling?

Transpile is a portmanteau of the words translate and compile. Compilers typically compile a written programming language into incomprehensible[1] machine code. A transpiler is a special kind of compiler that translates from the source code of one programming language to the source code of another.

1

To a human, anyway.

2.1.1. Compiling to JavaScript languages

Transpilers have been around for some time, but they exploded onto the JavaScript scene in 2009 with the introduction of CoffeeScript (http://coffeescript.org). CoffeeScript is a compile-to-JavaScript language created by Jeremy Ashkenas, who is also known for creating the popular JavaScript libraries Underscore and Backbone. It takes many cues from Ruby, Python, and Haskell, and focuses on the “good parts” of JavaScript made popular by Douglas Crockford in his book JavaScript: The Good Parts (O’Reilly Media, 2008). CoffeeScript achieved this by hiding many of what users refer to as the warts of JavaScript and only exposing the safer parts.

CoffeeScript, however, is neither a subset nor a superset of JavaScript. It exposes a new syntax and many new concepts, some of which became inspiration for features in ES2015, such as arrow functions. Following CoffeeScript’s success, many other compile-to-JavaScript languages started showing up, such as ClojureScript, PureScript, TypeScript, and Elm, to name just a few.

JavaScript isn’t necessarily the best target for a language to compile to, but in order to run code on the web, there is no other choice. Recently a new technology was announced called WebAssembly (often shortened to wasm). WebAssembly promises to be a better compile-to target for frontend development than JavaScript, and if successful, could pave the way for even more diversity when choosing a language to run in the browser.

2.1.2. Where Babel fits in

At this point, you may be thinking, “Transpilers sound cool and all, but who cares? I’m reading a book on JavaScript, not a language that compiles to it.” Well, transpilers aren’t just used for languages that compile to JavaScript. They can also help you write ESNext code and use it in the browser today. Think about it: when another language compiles to JavaScript, it not only targets JavaScript, but a specific version of JavaScript. CoffeeScript, for example, targets ES3. So if a completely differently language can be transpiled into a specific version of JavaScript, shouldn’t another version of JavaScript be able to as well?

There are several transpilers for converting ESNext JavaScript into a suitable version that can be executed in the browser today. Two of the most commonly used are Traceur and Babel. Babel used to be called ES6to5 because it transpiled ES6 code into ES5 code, but after it started supporting all future JavaScript features, and considering that ES6’s name officially changed to ES2015, the team behind ES6to5 decided to change the project’s name to Babel.

2.2. Setting up Babel 6

Babel is available as an NPM (https://www.npmjs.com/) package and comes bundled with Node.js (https://nodejs.org/en/). You can download an installer for Node.js from their website. This book assumes you have Node.js version 4 or later installed and NPM version 3 or later. NPM comes bundled with Node.js and thus doesn’t require being installed separately.

In order to use Babel, you’ll set up a node.js package so you can install your required dependencies. With Node.js and NPM installed, open a command line program (Terminal .app in OSX or cmd.exe in Windows) and execute the following shell commands to initialize a new project (make sure you replace the placeholder project_name with the name of your project):[1]

1

The $ at the beginning indicates that this is a shell command meant to be executed in a command line program. The $ is not part of the actual command and should not be entered.

$ mkdir project_name
$ cd project_name
$ npm init –y

Let’s break this command down. The line mkdir project_name will make a new directory (folder) with the name you provide. Then cd project_name will change to the newly created directory for the project. Finally, npm init will initialize this as a new project. The –y flag tells NPM to skip asking questions and go with all the defaults.

You should now see a new file called package.json in your project indicating that this is a Node.js project. Now that you have a project initialized, you can set up Babel. Execute the following shell command to install Babel’s command line interface:[2]

2

The current version of Babel at the time of this writing is version 6.5.2. The instructions in this book are for Babel version 6.x which is a major change from version 5.x. You can constrain to some version of Babel 6 using the version range >=6.0.0 <7.0.0 e.g. npm install babel@">=6.0.0 <7.0.0"; see https://docs.npmjs.com/cli/install.

$ npm install babel-cli --save-dev

Beginning in version 6, Babel doesn’t do any transforming by default, and you must install plugins or presets for any transformations you want to apply. To use a plugin or preset, you must both install it in your project and specify its use in Babel’s configuration.

Babel uses a special file called .babelrc for its configuration. You must put this file in the project’s root and the contents of the file must be valid JSON. To specify that you want Babel to transpile all ES2015 features, you can use the ES2015 preset. Edit the .babelrc file so its contents are

{
  "presets": ["es2015"]
}

Now that you’ve told Babel to use the ES2015 preset, you must also install it:

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

You should now be ready to transpile some ES6 code! Test it out. First add a new folder in your project named src and add a new index.js file in it. Your project structure should now look like this:

project_name
 src
    index.js

Now add some ES2015 code to transpile. Add the following code to your index.js file:

let foo = "bar";

You can now tell Babel to transpile your source code. In your terminal, run the following command.

Listing 2.1. Compiling from src folder to a dist folder
$ babel src -d dist

After running this command, a new directory named dist should be created with the transpiled code inside. Let’s break the command down. When you specify babel src you are telling Babel to operate on the contents of the src directory. By default, Babel outputs the transpiled code to the terminal. When you add the –d <directory_name>, you can tell Babel to output the transpiled code to a directory instead.

The structure of your project should now look like this:

project_name
 dist
 index.js
 src
    index.js

The dist/index.js file contains the following transpiled code:

"use strict";

var foo = "bar";

2.3. The Babel configuration needed for this book

Each of the TC39 stages has a preset. You can include a preset for any of the five stages and Babel will be able to compile code that has reached that stage (or higher). For example, if you use the stage-2 preset, you could use features that have reached stages 2, 3, or 4, but not stages 0 or 1.

Because I can’t predict what stages each proposal will be at when you read this, please consult the TC39 stages links from lesson 1 to determine what presets you will need.

Alternatively you can go with stage 0 to grab everything, using the following .babelrc preset.

Listing 2.2. Babel stage-0 presets
{
  "presets": ["es2015", "stage-0"],
  "plugins": ["transform-decorators-legacy"],
  "sourceMaps": "inline"
}

In listing 2.2, you’re using the ES2015 and stage-0 presets to include all of ES2015 and all of the existing proposed features. You also need to include the transform-decorators-legacy plugin in order to transpile decorators. And finally you tell Babel to include inline source maps to make debugging easier. Now in order for Babel to use those plugins and presets, you need to install them:[1]

1

You can install them all at once instead of one at a time like I did. I did it this way for legibility in the small margins of a book.

$ npm install babel-preset-es2015 --save-dev
$ npm install babel-preset-stage-0 --save-dev
$ npm install babel-plugin-transform-decorators-legacy --save-dev

2.3.1. A note on source maps

In your Babel configuration you added a section for source maps. If you’re unfamiliar with source maps, they’re a technology invented to make it easier to debug minified code. Most production applications ship with their code minified to save bandwidth so that the app will load faster. This minified code can be a nightmare to debug, though, so source maps were invented to map code back to its original form. Compile-to-JavaScript languages started using source maps to show the original language’s source instead of the transpiled JavaScript, and Babel does as well. To learn more about source maps, see http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/.

2.3.2. Set up Babel as NPM script

You may not want to repeatedly tell Babel what folder to transpile from and to (like you did in listing 2.1). You can make your life easier by setting up an NPM script to do that for you. If you’re unfamiliar with how NPM scripts work, it’s really simple. In your NPM configuration file named package.json, there’s a special scripts section that allows you to specify shell commands that can be executed by their name. See https://docs.npmjs.com/misc/scripts for further information about NPM scripts.

There should already be a test script added to your package.json by default. If you open your package.json file and locate the scripts section, it should look like this:[1]

1

Depending on your operating system, it could look different.

"scripts": {
  "test": "echo "Error: no test specified" && exit 1"
},

You can add our Babel command as a script like so:

"scripts": {
  "test": "echo "Error: no test specified" && exit 1",
  "babel": "babel src –d dist",
},

Don’t forget to add the comma after the test command! You should now be able to execute this NPM script by executing the following shell command:

$ npm run babel

This is not only simpler and easier to remember, but you can also modify your Babel script as your needs evolve, and your command always remains the same.

Summary

In this lesson you learned what transpiling is and how it can be used to start using the ESNext features. You also learned how set up Babel to transpile the code in this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.103.5