Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Advanced JavaScript

You're reading from   Advanced JavaScript Speed up web development with the powerful features and benefits of JavaScript

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher
ISBN-13 9781789800104
Length 330 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Zachary Shute Zachary Shute
Author Profile Icon Zachary Shute
Zachary Shute
Arrow right icon
View More author details
Toc

Transpilation


Transpilation is defined as source-to-source compilation. Tools have been written to do this and they are called transpilers. Transpilers take the source code and convert it into another language. Transpilers are important for two reasons. First, not every browser supports every new syntax in ES6, and second, many developers use programming languages based off of JavaScript, such as CoffeeScript or TypeScript.

Note

The ES6 compatibility table can be found at https://kangax.github.io/compat-table/es6/.

Looking at the ES6 browser compatibility table clearly shows us that there are some holes in support. A transpiler allows us to write our code in ES6 and translate it into vanilla ES5, which works in every browser. It is critical to ensure that our code works on as many web platforms as possible. Transpilers can be an invaluable tool for ensuring compatibility.

Transpilers also allow us to develop web or server side applications in other programming languages. Languages such as TypeScript and CoffeeScript may not run natively in the browser; however, with a transpiler, we are able to build a full application in these languages and translate them into JavaScript for server or browser execution.

One of the most popular transpilers for JavaScript is Babel. Babel is a tool that was created to aid in the transpilation between different versions of JavaScript. Babel can be installed through the node package manager (npm). First, open your terminal and path to the folder containing your JavaScript project.

If there is no package.json file in this directory, we must create it. This can be done with the npm init command. The command-line interface will ask you for several entries so that you can fill out the defaults of the package.json file. You can enter the values or simply press the return key and accept the default values.

To install the Babel command-line interface, use the following command: npm install --save-dev babel-cli. After that has concluded, the babel-cli field will have been added to the devDependencies object in the package.json file:

{
 "devDependencies": {
   "babel-cli": "^6.26.0"
 }
}

Snippet 1.73: Adding the first dependency

This command only installed the base Babel with no plugins for transpiling between versions of JavaScript. To install the plugin to transpile to ECMAScript 2015, use the npm install --save-dev babel-preset-es2015 command. Once the command finishes running, our package.json file will contain another dependency:

"devDependencies": {
 "babel-cli": "^6.26.0",
 "babel-preset-es2015": "^6.24.1"
}

Snippet 1.74: Adding the second dependency

This installs the ES6 presets. To use these presets, we must tell Babel to configure itself with these presets. Create a file called .babelrc. Note the leading period in the name. The .babelrc file is Babel's configuration file. This is where we tell Babel what presets, plugins, and so on, we are going to use. Once created, add the following contents to the file:

{
  "presets": ["es2015"]
}

Snippet 1.75: Installing the ES6 presets

Babel- Transpiling

Now that Babel has been configured, we must create the code file to transpile. In the root folder of your project, create a file called app.js. In this file, paste the following ES6 code:

const sum5 = inputNumber  => inputNumber + 5;
console.log( `The sum of 5 and 5 is ${sum5(5)}!`);

Snippet 1.76: Pasting the code

Now that Babel has been configured and we have a file that we wish to transpile, we need to update our package.json file to add a transpile script for npm. Add the following lines to your package.json file:

"scripts": {
 "transpile": "babel app.js --out-file app.transpiled.js --source-maps"
}

Snippet 1.77: Update the package.json file

The scripts object allows us to run these commands from npm. We are going to name the npm script transpile and it will run the command chain babel app.js --out-file app.transpiled.js --source-maps. App.js is our input file. The --out-file command specifies the output file for compilation. App.transpiled.js is our output file. Lastly, --source-maps creates a source map file. This file tells the browser which line of transpiled code corresponds to which lines of the original source. This allows us to debug directly in the original source file, that is, app.js.

Now that we have everything set up, we can run our transpile script by typing npm run transpile into the terminal window. This will transpile our code from app.js into app.transpiled.js, creating or updating the file as needed. Upon examination, we can see that the code in app.transpiled.js has been converted into ES5 format. You can run the code in both files and see that the output is the same.

Babel has many plugins and presets for different modules and JavaScript releases. There are enough ways to set up and run Babel that we could write an entire book about it. This was just a small preview for converting ES6 code to ES5. For full documentation and information on Babel and the uses of each plugin, visit the documentation.

Note

Take a look at Babel's home page at https://babeljs.io.

In summary, transpilers allow you to do source to source compiling. This is very useful because it allows us to compile ES6 code to ES5 when we need to deploy on a platform that does not yet support ES6. The most popular and most powerful JavaScript transpiler is Babel. Babel can be set up on the command line to allow us to build entire projects in different versions of JavaScript.

Exercise 14: Transpiling ES6 Code

Your office team has written your website code in ES6, but some devices that users are using do not support ES6. This means that you must either rewrite your entire code base in ES5 or use a transpiler to convert it to ES5. Take the ES6 code written in the Upgrading Arrow Functions section and transpile it into ES5 with Babel. Run the original and transpiled code and compare the output.

To demonstrate Babel's ability to transpile code from ES6 to ES5, perform the following steps:

Ensure that Node.js is already installed before you start.

  1. Install Node.js if it is not already installed.

  2. Set up a Node.js project with the command line command npm init.

  3. Put the code from the Upgrading Arrow Functions section into the app.js file.

  4. Install Babel and the Babel ES6 plugin with npm install.

  5. Configure Babel by adding a .babelrc file with the es2015 preset.

  6. Add a transpile script to package.json that calls Babel and transpiles from app.js to app.transpiled.js.

  7. Run the transpile script.

  8. Run the code in app.transpiled.js.

Code

package.json:
// File 1: package.json
{
 "scripts": {
   "transpile": "babel ./app.js --out-file app.transpiled.js --source-maps"
 },
 "devDependencies": {
   "babel-cli": "^6.26.0",
   "babel-preset-es2015": "^6.24.1"
 }
}

Snippet 1.78: Package.json config file

.babelrc:

// File 2: .babelrc
{ "presets": ["es2015"] }

Snippet 1.79: Babel config file

app.transpiled.js:

// File 3: app.transpiled.js
var fn1 = function fn1(a, b) { … };
var fn2 = function fn2(a, b) { … };
var fn3 = function fn3(a) { … };
var fn4 = function fn4() { … };
var fn5 = function fn5(a) { … };

Snippet 1.80: Fully transpiled code

Outcome

Figure 1.16: Transpiled script output

You have successfully implemented Babel's ability to transpile code from ES6 to ES5.

In this section, we discussed the concept of transpilation. We introduced the transpiler Babel and walked through how to install Babel. We discussed the basic steps to set up Babel to transpile ES6 into ES5 compatible code and, in the activity, built a simple Node.js project with ES6 code to test Babel.

You have been reading a chapter from
Advanced JavaScript
Published in: Jan 2019
Publisher:
ISBN-13: 9781789800104
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image