Babel presets, plugins and es6

babeljsx
Back

You must have seen the .babelrc file in the project root folder. It helps babel transpile the es6 code. Let’s Learn more about it.

what is babel

From https://babeljs.io/, Babel is a JavaScript compiler.

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments.

How does it transpile

let's set up a sample folder with babel to convert es6 codes.

mkdir babel-demo
cd babel-demo
npm init -y

Next, add babel as dev dependency.

npm install --save-dev @babel/core @babel/cli

Let's create a file main.js that will have es6 codes.

let user = {
  fname: 'binod',
  lname: 'swain'
}
// object destructuring
const { name, lname } = user

console.log(`${fname} ${lname}`)

Install helper plugin for object destructuring.

npm install --save-dev @babel/plugin-transform-destructuring

Update .babelrc file with the same plugin.

{
  "plugins": ["@babel/plugin-transform-destructuring"]
}

Now transpile main.js to bundle.js file.

npx babel main.js -o bundle.js

Babel needs the mentioned plugin to transpile the es6 codes from main.js to output. In the absence of the plugin, it will just copy the same content to the output file. To verify, delete .babelrc file and run babel. The same content will be present in main.js and bundle.js. We can mention plugins in .babelrc to include more es6 features in our code. Babel provides a better way to include common plugins with the help of presets.

What is babel-presets

babel-presets contains common plugins that will be automatically installed and let you use the latest JS as needed by the mentioned target environment.

List of official presets from Babel.

Configuring babel-preset

Install npm dev dependency.

npm install --save-dev @babel/preset-env

This will add all dependent helpers and plugins modules in node_modules. Next, Add to presets of .babelrc file.

{
  presets: ['@babel/preset-env']
}
© Binod SwainRSS