Babel JS - a JavaScript compilation tool
Babel is a JavaScript transpilation tool that enables developers to take advantage of the latest features of the language, converting them to versions compatible with older browsers. It works through plugins and presets, such as @babel/preset-env, which automatically adapt code to target environments. Babel also supports the addition of polyfills, integration with build tools like Webpack, and allows modern programming without compatibility concerns.
Main features and applications of Babel JS
Transpilation
Babel compiles JavaScript code from modern ECMAScript standards (e.g. ES6, ES7) into versions that are supported by all browsers. This allows developers to take advantage of new language features without compatibility concerns.
Polyfills
Babel can add polyfills that emulate new JavaScript features in older browsers. For example, with Babel, we can use Promise in browsers that don’t have native support for the feature.
Plugins
Babel is modular and plugin-based. Developers can add specific plugins that transpile specific JavaScript functions. Examples of plugins include: @babel/plugin-transform-arrow-functions for transpiling arrow functions or @babel/plugin-transform-async-to-generator for transpiling asynchronous functions.
Presets
Babel offers sets of plugins called presets that can be easily configured. The most popular preset is @babel/preset-env, which automatically determines which plugins are needed depending on the targeted environments.
Integration with build tools
Babel easily integrates with popular project build tools such as Webpack, Gulp and Rollup. This makes it possible to automate the transpilation process during project build.
Installing Babel JS
Babel is available as a Node module. Installation, as you would expect, is done via npm:
npm install babel-cli
Example of Babel configuration
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-transform-runtime"]
}
The example shows how Babel can be configured using a configuration file. It shows how to use the @babel/preset-env
preset and the @babel/plugin-transform-runtime plugin
to transpile modern JavaScript code to a version compatible with older browsers. This configuration is a basic example of how to get started with Babel in a project.
An example of an advanced Babel JS configuration:
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": ["last 2 versions", "ie >= 11"]
},
"useBuiltIns": "usage",
"corejs": 3
}],
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-class-properties"
]
}
The example of an advanced Babel configuration shows how to adapt Babel to transpile modern JavaScript and JSX into versions compatible with different browsers, including older versions of Internet Explorer. The configuration uses the @babel/preset-env
and @babel/preset-react
presets, and the @babel/plugin-transform-runtime
and @babel/plugin-proposal-class-properties
plugins , to provide code optimisation, automatic addition of polyfills and support for ES6 classes. Targets specify which browsers are to be supported, and useBuiltIns
in combination with corejs
ensures that only the necessary polyfills are added.
Classes in Babel JS
Below is an example of an ES6 class:
class Person {
// Konstruktor - wywoływany podczas tworzenia nowej instancji klasy
constructor(name, age) {
this.name = name; // Ustawianie właściwości 'name'
this.age = age; // Ustawianie właściwości 'age'
}
// Metoda klasy
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
// Inna metoda klasy
haveBirthday() {
this.age += 1;
console.log(`Happy Birthday! I am now ${this.age} years old.`);
}
}
// Tworzenie nowej instancji klasy
const person1 = new Person('Alice', 30);
// Wywoływanie metod instancji
person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.
person1.haveBirthday(); // Output: Happy Birthday! I am now 31 years old.
Class declaration: The keyword class is used to define a class and its name is Person.
Constructor: The constructor method is a special method for initialising newly created objects. It takes two parameters, name and age, and assigns them to the properties of the instance.
Methods: greet and haveBirthday are class methods that can be called on instances of the class.
Creating an instance: new Person(‘Alice’, 30) creates a new instance of the Person class with name ‘Alice’ and age 30.
Calling methods: The methods greet and haveBirthday are called on the person1 instance.
Webpack configuration with Babel:
The following configuration enables Webpack to process JavaScript files with Babel so that modern JavaScript features can be used in the source code and the resulting code is compatible with a wide range of browsers.
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
};
FAQ – Frequently Asked Questions
Initialise the project: If you have not already done so, initialise the project using npm:npm init -y
Install Babel CLI and core: Install Babel CLI and Babel core using npm:npm install --save-dev @babel/core @babel/cli
Install Babel presets: For example, to use the preset @babel/preset-env
, run:npm install --save-dev @babel/preset-env
Create a Babel configuration file: Create a .babelrc
configuration file in the project root directory and add presets to it:
jsonCopy the code{ ‘presets’:
[‘@babel/preset-env’] }
Code transpilation: To transpile code, use the Babel CLI. For example, to convert a script.js
file to a compatible version, run:npx babel script.js --out-file script-compiled.js
Babel JS is mainly used to transpile modern JavaScript to older versions so that the code is compatible with all browsers. It allows you to use the latest features of the language, such as classes, arrow functions or asynchronous functions, and automatically adds polyfills for missing features in older browsers. Babel also supports JSX and TSX transpilation, which is useful when working with React and TypeScript, and can optimise code with various plugins. In practice, this means installing Babel in a project, configuring the relevant presets and plugins, and then transpiling the code before deployment.