Skip to content
Related Articles

Related Articles

Babel in ES6

Improve Article
Save Article
Like Article
  • Last Updated : 06 Dec, 2021

A Babel transpiler is a free, open-source tool that converts ECMAScript 2015 (ES6) code to a backward-compatible version of JavaScript that can run on old and new browsers.

FLOW OF COMPILATION 

JavaScript is the language that the browser understands. We use a variety of browsers to run our applications, including Chrome, Firefox, Internet Explorer, Microsoft Edge, Opera, and UC Browser. We have had ES6, ES7, and ES8 since ES5. As part of the ES6 release, many new features were introduced that are not yet fully supported by all browsers. It is uncertain when all browsers will be able to support all the ES versions released. In case we plan on using ES6 or ES7 or ES8 features in our code, the code might break in some older browsers due to a lack of support for new features. Thus, we require a tool that compiles our final code in ES5. This is where Babel comes in.

Transpilling: Translating programming languages into a specific target language is called transpilling.  A Babel- transpiler can parse the modern JavaScript code and rewrite it using older syntax constructs so that it’ll also work on outdated browsers. In addition to syntax constructs and operators, language enhancements may include functions as well. For example, Math. trunc(n) removes the decimal part of a number, e.g. Math. trunc(1.47) returns 1. Some (outdated) JavaScript engines do not support Math. trunc, so such code will fail. Since we’re talking about new functions, not syntax changes, there’s no need to transpile anything. All we need to do is declare the function. When the new feature is a method or object, we need to use Babel-polyfill along with transpilation to make it work on older browsers.

Let’s consider the arrow function feature of ES6 to understand Babel. For example, you might want this arrow function Javascript code 

Javascript




(x) => x + 1;

to be compiled into, browser supported JavaScript code:

Javascript




"use strict";
  
(function (x) {
  
  return x + 1;
  
});

The process involves three primary steps:

1. Parsing: Babel takes the source code and parses it as an  AST ( Abstract Syntax Tree). An AST is a data structure that represents the structure of a source code as a tree.

2. Transforming:  Babel transforms the AST from the last step and manipulates it such that the resultant AST represents browser-compatible code.

3. Code Generation: A browser-supported code is derived from the AST generated from the last step in Babel.

Javascript




"use strict";
  
(function (x) {
  
  return x + 1;
  
});

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!