Babel is a JavaScript compiler
Babel: Principles of operation, purpose, and application.
Babel is a JavaScript compiler. It is a toolchain primarily used to transform ECMAScript 2015+ JavaScript code into a version that is compatible with older browsers and environments. Below, I will highlight the main features of Babel.
Now, I will present a small example to make this clearer.
JavaScript
// Passing an ES2015 arrow function to Babel
[1, 2, 3]. map(n => n + 1);
// Babel returns
[1, 2, 3]. map(function(n) {return n + 1;});
Babel not only transforms ECMAScript but also compiles JSX, React.JS, TypeScript, WebPack, and other similar tools. Almost all modern libraries and frameworks use Babel. That's why it's important to know about Babel. It has many tools that make work easier. We will look at an incomplete list of them.
1. First, you need to install it in your project.
npm install --save-dev @babel/core @babel/cli @babel/preset-env
2. Create a babel.config.json file in your project's root directory (this is required for version v7.8.0 and higher).
babel.config.json
{ "presets": [ [ "@babel/preset-env", { "targets": { "edge": "17", "firefox": "60", "chrome": "67", "safari": "11.1" }, "useBuiltIns": "usage", "corejs": "3.6.5" } ] ] }
3. Now create a JS (test.js) file and import some ECMAScript code. Then run the following command in your terminal.
npx babel test.js
If you follow these steps, Babel will be installed in your project, making JavaScript code compatible with different browsers and environments. Also, you can use the new JavaScript features without neglecting support for old browsers.
By installing the proper configuration and a few simple commands, you will get code that can work with all old browsers and previous technologies without any difficulty.
This way, you ensure your code's accessibility to a wider audience while working on both modern technologies and older platforms.
Babel is a powerful and flexible tool that has many configuration options. Here are some of the main configurations we can use for different needs:
Presets are one of Babel's main configurations that provide transformation rules for different JavaScript versions:
{ "presets": [ [ "@babel/preset-env", { "targets": { "chrome": "67", "firefox": "60" }, "useBuiltIns": "usage", "corejs": "3.6.5" } ] ]}
Plugins allow for more detailed transformations, such as transforming JSX or TypeScript:
{ "plugins": ["@babel/plugin-transform-react-jsx"]}
This configuration hints to Babel which browsers the features should be transformed for:
{ "targets": { "chrome": "67", "firefox": "60" }}
This option determines whether Babel should use polyfills available for new JavaScript features.
{ "useBuiltIns": "usage", "corejs": "3.6.5"}
This option configures the module system by determining whether Babel should transform the module code.
{ "modules": false}
This option allows you to specify files or categories that should be ignored by Babel.
{ "ignore": ["node_modules"]}
Source maps provide an easier way to monitor and debug transformed code by relating it to the original code.
{ "sourceMaps": "inline"}
This option allows you to enable or disable caching during the transformation process.
{ "cacheDirectory": true}
Thus, you can tailor Babel to your project's needs by applying different presets, plugins, and configuration parameters.
Babel CLI (Command Line Interface) is one of Babel's tools that allows you to work with the JavaScript code transformation process via the command terminal.
It helps transform JavaScript code into various formats based on any configuration. By using Babel CLI, we can quickly apply changes to multiple files or modules.
To use Babel CLI, you need to install it in your project with the following command:
npm install --save-dev @babel/cli @babel/core
The main command to run Babel for basic code transformation is:
npx babel input.js --out-file output.js
This command will transform the `input.js` file and save the result as `output.js`.
If you want to transform several files at once, you can use the *
wildcard:
npx babel src/*.js --out-dir lib
This command will transform all JavaScript files in the `src` folder and place the transformed results in the `lib` folder.
Source maps help identify errors in the transformed code.
If you want to generate source maps, add the `--source-maps` option:
npx babel src --out-dir lib --source-maps
This command will generate source maps along with the transformed code.
If you want to use the `babel.config.json` configuration file, you can easily import it with the CLI command:
npx babel src --out-dir lib --config-file babel.config.json
This command will use your `babel.config.json` file to transform the code according to the specified configurations.
Besides configuration files, you can also use plugins and presets with CLI:
For example:
npx babel src --out-dir lib --plugins @babel/plugin-transform-arrow-functions
This command will use the `@babel/plugin-transform-arrow-functions` plugin to transform all arrow functions.
Here are some other useful transformations in CLI:
npx babel src --out-dir lib --modules commonjs
npx babel src --out-dir lib --presets @babel/preset-env
npx babel src --out-dir lib --ignore "node_modules/**"
Thus, Babel CLI has many features that simplify the transformation of JavaScript code through various modules, plugins, presets, and configurations.
Using the CLI allows for flexible and fast development of JavaScript applications, making the process easier or more convenient.
Babel plugins enable transforming JavaScript code in specific ways. The plugins work with Babel to perform the necessary transformations. Here are several essential Babel plugins that may be helpful:
This plugin transforms ES6 arrow functions into regular functions. It is particularly useful when you want to ensure compatibility with older browsers.
npx babel src --out-dir lib --plugins @babel/plugin-transform-arrow-functions
Example:
const add = (a, b) => a + b;
Result after transformation:
var add = function(a, b) { return a + b;};
This plugin transforms ES6 template literals (with backticks) into standard string concatenation. It's useful when you need compatibility with older browsers.
npx babel src --out-dir lib --plugins @babel/plugin-transform-template-literals
Example:
let name = 'John';let message = `Hello, ${name}!`;
Result after transformation:
var name = 'John';var message = 'Hello, ' + name + '!';
This plugin transforms ES6 classes into regular functional constructors. This is important, especially in older JavaScript environments where classes are not supported.
npx babel src --out-dir lib --plugins @babel/plugin-transform-classes
Example:
class Person { constructor(name) { this.name = name; }}
Result after transformation:
function Person(name) { this.name = name;}
This plugin supports the declaration of class properties in JavaScript without using a constructor. This feature was added with ES6, but does not work in older browsers.
npx babel src --out-dir lib --plugins @babel/plugin-proposal-class-properties
Example:
class Car { brand = 'Toyota';}
Result after transformation:
function Car() { this.brand = 'Toyota';}
This plugin is essential for React projects as it supports JSX syntax (JavaScript XML), which allows writing HTML-like code inside JavaScript.
npx babel src --out-dir lib --plugins @babel/plugin-syntax-jsx
Example:
const element = <հ1>Hello World</հ1>;
Result after transformation:
varelement= React.createElement('h1', null, 'Hello, world!');
This plugin is necessary when working with code that uses Generators and async/await, ensuring compatibility with older browsers.
npxbabel src--out-dir lib --plugins@babel/plugin-transform-regenerator
Example:
async function fetchData() { let data = await fetch('https://api.example.com'); return data;}
Result after transformation:
Thus, Babel plugins significantly expand Babel’s capabilities, supporting a wide range of the latest JavaScript features and functionalities. By using these plugins, you can create a more convenient development environment and ensure compatibility between browsers and different versions of JavaScript.
You can see an example in my GitHnub