Introduction to Babel
The well-known transpiler Babel essentially enables the use of future JavaScript in current browsers.
Simply put, it can translate the most recent JavaScript code into a format that the browser can understand.
The most recent standard that JavaScript adheres to is ES2020, which is not completely supported by all browsers.
As a result, we use a tool like “babel” to transform it into code that today’s browsers can understand.
What is a transpiler?
It is a tool used to translate one source code level into another source code level.
It is also referred to as a source-to-source compiler because of this.
Given that one code functions with a certain browser version and the other does not, both codes are equal in nature.
A compiler generally turns code into lower level code, in contrast to a transpiler, which converts source code into another source code at the same abstraction level.
This distinction between the two is important. Similar to Java, byte code, which is lower level and not equivalent, is created from source code.
Why is Babel necessary?
The biggest benefit of babel is that it allows us to leverage the most recent features that JavaScript has to offer without having to worry about whether they will function in the browser or not.
Aspects of Babel
Babel-Plugins: If the environment is known, the configuration information for the plugins allows Babel to transpile the code that supports a variety of plugins.
Babel-Presets: Babel presets are a collection of plugins that tell Babel how to transpile. if the surroundings are known.
Babel-Polyfills: When methods and objects cannot be translated, we can utilise babel-polyfill to make features easier to use in any browser.
Babel-Polyfills: There are numerous commands available in Babel’s command-line interface that make it simple to compile code. Additionally, it offers tools like plugins and presets that may be used in conjunction with the command to make it simple to transpile the code all at once.
Code:
// sample new version javascript code const fun = (x) => {x*2}; const a = () => {}; const b = (x) => x; [1, 2, 3].map((n)=> n+1);
Because parts of the aforementioned code may not work properly in all browsers, after transpiling it though Babel, we will obtain:
// after transpiling "use strict"; var fun = function fun(x) { x * 2; }; var a = function a() {}; var b = function b(x) { return x; }; [1, 2, 3].map(function (n) { return n + 1; });