Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
1.1.
Babel as Javascript Compiler
1.2.
What is a transpiler?
2.
Why is Babel important?
2.1.
Features of Babel
3.
Advantages of Babel
4.
Disadvantages of Babel
5.
How to run Babel?
6.
Create a simple React Project using Babel
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

Introduction to Babel

Author Sneha Mallik
1 upvote

Introduction 

Babel is a transpiler for JavaScript. Babel's primary goal is to convert ECMAScript 2015+ (ES6+) code into a backward compatible JavaScript version that previous JavaScript engines can run. In the proposal stage, Babel converts (transpile) JSX syntax, Typescript, Code Compression, and any other syntaxes. 

For instance, arrow functions defined in ES6 are transformed into standard function declarations. Babel provides polyfills to provide support for capabilities that aren't available in JavaScript contexts. Static methods such as Array.form and built-ins such as Promise are only accessible in ES6+, but they can be used in previous contexts with the help of a Babel polyfill.

Babel is a well-known transpiler that enables us to use future JavaScript in current browsers. It can translate the most recent version of JavaScript code into a format that the browser recognizes in the simplest form. The most recent standard version of JavaScript is ES2020, which is not entirely supported by all browsers. As a result, we use a tool like 'babel' to transform it into code that today's browsers can understand.

Also See, Dropdown in React JS

 

Babel as Javascript Compiler

Babel is a toolchain that converts ECMAScript 2015+ code into a backward-compatible version of Javascript for use in both present and older browsers and environments. The following are some of the essential things Babel can accomplish for you:

  • It changes the syntax.
  • Features that aren't present in your target environment will be polyfilled (through a third-party polyfill such as core-js).
  • Transformations of source code (codemods).

What is a transpiler?

It's a program that converts one level of source code into another level of source code. It's also known as a source-to-source compiler for this reason. Both codes are equivalent in nature, even though one works with a specific browser version and the other does not.

Note that a compiler is not the same as a transpiler in that a transpiler turns source code into another source code at the same abstraction level, but a compiler converts code into lower-level code in general. The source code is transformed to byte code, which is lower level and not equivalent, much like in Java.

Why is Babel important?

The primary reason we need babel is that it allows us to take advantage of the latest JavaScript features without worrying whether or not they will work in the browser.

Let us go over the features of Babel. The most significant basic functionalities of Babel are the following:

Features of Babel

  • The Babel-Plugins

The 'plugins' and 'presets' are Babel's configuration details for transpiling the code. Babel has several plugins that babel supports that can be used separately if the code's environment is known.

  • The Babel-Presets

Babel presets are a collection of plugins that tell the babel-transpiler how to transpile in a certain mode. We must utilize presets to specify the environment in which the code should be transformed. E.g., the ES2015 preset will convert the code to ES5.

  • The Babel-Cli

Babel-cli comes with a set of commands that make it simple to compile code from the command line. It also includes features such as plugins and presets that may be used in conjunction with the command, making it simple to transpile the code all at once.

  • The Babel-Polyfills

Some aspects, such as methods and objects, are not able to be transpiled. In these cases, we can utilize babel-polyfill to make it easier to use features in any browser. Consider the case of promises: we need to utilize polyfills to make the feature operate in older browsers.

Advantages of Babel

Here, we'll go over the various advantages of using BabelJS.

  • BabelJS offers backward compatibility to all of JavaScript's new features and may be used in any browser.
  • BabelJS can transpile to the next version of JavaScript, such as ES6, ES7, ESNext, and so on.
  • BabelJS may be used in conjunction with gulp, webpack, flow, react, typescript, and other tools, making it extremely powerful and useful for large projects.
  • BabelJS can also be compiled in JSX form and works with react JSX syntax.
  • Plugins, polyfills, and babel-cli are all supported by BabelJS, making it simple to deal with large projects.

Disadvantages of Babel

Let us know about the various drawbacks of utilising BabelJS:

  • When BabelJS code is transpiled, the syntax is changed, making the code more difficult to understand when it is released in production.
  • When compared to the original code, the transpiled code is larger.
  • Because not all ES6/ES7/ES8 or forthcoming new features can be transpiled, we must rely on polyfill to make it work in earlier browsers.

How to run Babel?

We can run Babel in the following four ways:-

  • @babel/core
  • @babel/register
  • @babel/core
  • webpack babel-loader

 

In Node.js, @babel/register is frequently used. When the required code is executed, it causes babel to run dynamically. We won't deal with the @babel/register method because it's not popular to execute babel in React.

Create a simple React Project using Babel

Let's start by making a simple project:

First, let us create a directory, and then we will include package.json into the directory.

mkdir test-babel-how
cd test-babel-how
npm init -y 

 

We will then install the necessary packages needed:

 

npm i @babel/core @babel/cli @babel/plugin-transform-arrow-functions @babel/plugin-transform-template-literals @babel/preset-react

 

Now, we will create an src folder and create myCode.js in the src folder.

test-babel-how
|
-- node_modules
-- src
    |
    -- myCode.js
-- package-lock.json
-- package.json
//myCode.js file

const element = <div>To conduct a babel test</div>; // 1
const text = `element type is ${element.type}`; // 2
const add = (a,b)> a + b; // 3

 

We'll do the following:

1) Use the react preset to transpile JSX syntax.

2) Use the template literal plugin to transpile template literals.

3) Using the arrow function plugin, transpile the arrow function.

 

  1. Use the react preset to transpile JSX syntax.
// The src/myCode.js location is specified by the Babel command.
npx babel src/myCode.js
 
// We're utilising the preset @babel/preset-react.
--presets=@babel/preset-react

/*
    @babel/plugin-transform-template-literals & 
    @babel/plugin-transform-arrow-functions are the two plugins 
    we're using here.
*/
--plugins=@babel/plugin-transform-template-literals, @babel/plugin-transform-arrow-functions

 

The following is the output in the terminal:

"use strict";
// The JSX syntax is rendered to the createElement function call.
const element = /*#__PURE__*/React.createElement("div", null, "To conduct a babel test"
);

// A concat method is used to transform a template literal to a string.
const text = "element type is ".concat(element.type); 

// The arrow function is transformed into a regular function.
const add = (a, b) > a + b; 

 

2. Use the template literal plugin to transpile template literals.

We will now install the packages to use 'webpack'.

npm i webpack webpack-cli babel-loader

 

We will create the babel.config.js file.

const presets = ['@babel/preset-react'];
const plugins = [
    '@babel/plugin-transform-template-literals',
    '@babel/plugin-transform-arrow-functions'
];

module.exports = { presets, plugins };

 

We create a config file named babel.config.js to specify presets and plugins instead of running them in the terminal.

 

We will create a file called webpack.config.js.

const path = require('path');
module.exports = {
    // Using webpack, specify a file to bundle
    entry: './src/myCode.js', 

    // Save the output to the file dist/code.bundle.js
    output: {
        path: path.resolve(__dirname, 'dist'), 
        filename: 'code.bundle.js',
    },

    // Handle JavaScript files with babel-loader
    module: {
        rules: [{ test: /\.js$/, use: 'babel-loader'}],
    },

    /*
    For performance reasons, webpack compresses the JavaScript 
    file by default. But first, let's see if the output is as 
    expected without optimising (compressing JavaScript file)
    */
    optimization: { minimizer: []} , 
}

 

We will now use the configuration in the babel.config.js file. To execute the webpack, run:

npx webpack 

 

The output of dist/code.bundle.js is as follows:

// webpackBootstrap
(function(modules) { 

 
    // The module cache
    var installedModules = {};
    (function(module, exports) {

    const element = /*#__PURE__*/React.createElement("div", null, 
    "To conduct a babel test");
    const text = "element type is ".concat(element.type);
    const add = (a, b) > a + b;
    })
]);

 

Here, we find out that the generated output is the same.

3. Using the arrow function plugin, transpile the arrow function.

To use the @babel/core directly. @babel/core is required to run babel, and we utilize it indirectly through @babel/cli and babel-loader.

 

To create the runBabel.js file:-

// To get the @babel/core module first.
const babel = require('@babel/core'); 
const fs = require('fs');

const filename = './src/myCode.js';

// To get the myCode.js file to compile
const source = fs.readFileSync(filename, 'utf8');

// Setup presets and plugins
const presets = ['@babel/preset-react']; 
const plugins = [
    '@babel/plugin-transform-template-literals',
    '@babel/plugin-transform-arrow-functions',
];

// To use the transformSync function to run babel
const { code } = babel.transformSync(source, { 
    filename,
    presets,
    plugins,

    // Prevent the use of the babel.config.js configuration file
    configFile: false,
});

// Output the code that has been transformed
console.log(code);

 

Now, we run the above file.

node runBabel.js

 

In the terminal, look at the same output.

const element = /*#__PURE__*/React.createElement("div", null, "To conduct a babel test"
); 
const text = "element type is ".concat(element.type); 
const add = (a, b) > a + b; 

Frequently Asked Questions

1. What is meant by 'BABEL'?

Ans: Babel is one of the most widely used JavaScript transpilers. It's mainly used to transform ES6 plus code into a backward-compatible version of JavaScript that older JavaScript engines can execute.

 

2. What do you mean by a module in babel?

Ans: Module is a rule-based object containing characteristics such as test, include, loader, and query.

  • All js files ending in .js and .jsx will be included in the test.
  • It has a pattern that looks for .js and .jsx at the end of the specified entry point.
  • Include specifies the location of the files to be searched.
  • The loader uses Babel-loader to compile programs.
  • The presets property of the query is an array with the value env – es5 or es6 or es7. As a preset, we utilized es2015 and React.

 

3. Which are the companies using Babel?

Ans: Babel is supposedly used by 1753 companies, including Instagram, Facebook, Robinhood, Discord, etc.
 

4. What is Babel-polyfill?

Ans: Promises, maps are among the new features that are added to JavaScript. The features can be used on arrays; however, they will not be converted if they are used and transpiled with babel. If the new feature is a method or object, we must use Babel-polyfill, a piece of code in combination with transpiling to make it compatible with earlier browsers.

Features of ECMAScript that can be polyfilled are:

Promises, Map, Set, Symbol, Weakmap, Weakset, includes, Array.from, Array.of, Array#find, Array.buffer, Array#findIndex, Object.assign, Object.entries, Object.values
 

5. What is the difference between webpack and babel?

Ans: Babel belongs to the "JavaScript Compilers" category, but Webpack belongs to the "JS Build Tools / JS Task Runners" category. We can think of Webpack as a big translator if Babel is a transpiler (translator) for JS. Webpack gathers a large number of modules into a small number of assets. Webpack frequently uses Babel as one of its jobs.

Backend: We use Babel to work with Node.js and employ the most advanced JS syntax (ES6/7) possible.

Frontend: We convert JS code and many other assets into a few small bundle files that our users can download when they first load our webpage using Webpack (which uses Babel and other things). For example, Create-react-app uses Webpack and Babel to build the application.

Key Takeaways

In this blog, we went over the fundamentals of babel. Since ECMAScript 2015 (ES6) release, the JavaScript community has released a new version nearly every year (ECMAScript 2016, 2017, 2018). As a result, Babel's transpiling capabilities are an essential tool in today's rapidly evolving JavaScript community. We went over three different ways to run Babel in this blog. Babel is a workhorse behind the scenes, ensuring that we can design compact and expressive React components using JSX. It also addresses any concerns with backward compatibility that may arise while utilizing new JavaScript syntax in older browsers. 

Enroll in our Full Stack Web Development Course — Node.js + HTML/CSS/JS to deeply understand the concept of babel in Web Development. 

Credits: GIPHY

Happy Developing!

Live masterclass