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.
- 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!