Babel 7: Configuration, Preset, and Plugin Usage

Ashan Dhananjaya
6 min readDec 2, 2019

--

Often the developer wants to use the latest in JavaScript, but is frustrated by the lack of support in browsers or the Node.js platform. The good news is that we can generate compatible code through Babel , the most widely used JavaScript compiler in the community. Babel version 7 is about to be released with several enhancements and new features, including support for the TypeScript language. In this article we learned how to configure it and use plugins to add features still proposed in the JavaScript language.

Prerequisite

To use Babel we need Node.js installed. We strongly recommend using the latest version (pair) available. This article used version 8.9.3. There are several ways to install Node.js, you can consult them at https://nodejs.org/en/ .

Babel 7 no longer supports Node.js versions 0.10, 0.12 and 5.

Now that we know which version of Node.js to use we can move on to the project structure.

Project Structure

Our next step will be to create the folder my-app and within it the subfolder app-src. This folder will contain all the files of the project, those that will be compiled by Babel. Let's enjoy and also create the file my-app/app-src/indedx.js:

my-app
├── app-src
│ └── index.js

Inside the folder my-appwe will create the file package.jsonby the command:

npm init -y

Excellent, we will have the following structure:

my-app
├── app-src
│ └── index.js
└── package.json

For those who have never used Node.js, understand package.json as a various metadata holder for all modules used by the application, including scripts created by the developer to automate tasks .

Installing Babel 7

One of the changes from version 6 to version 7 is the use of scoped packages .

At the time of publication of this article, the version of Babel used was 7.7.4.

We installed the modules coreand clithis way:

npm install -S @babel/core @babel/cli

O @babel/coreis the nerve center of the babel. Already @babel/cliis the command line client that allows us to interact with @babel/core.

Calling babel-cli through a script

Now that we have the dependencies downloaded, we need to create a script that calls us babel to target the folder app-src.

Let’s change my-app/package.json:

// code before the script
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "babel app-src -d app --source-maps",
"watch": "babel app-src -d app --source-maps --watch"
},
// code after the script

Within the object assigned to the property we "scripts"add two more properties, a "build"and a "watch".

The first script will compile all files within app-srceach time it runs, the second script will monitor the files in the folder in real time app-srcand, if any file is modified, will trigger the compilation process without having to worry about it. Regardless of the script called, the files resulting from the compilation process will be inside the folder my-app/app.

The parameter --source-mapsis important as it will allow you to debug the generated script by pointing the error line in the original file and not in the compiled file.

Let’s change the file my-app/app-src/index.jsand add a humble call to console.log:

// my-app/app-src/index.jsconsole.log('I was compiled by Babel 7.');

Now, inside the folder my-app, through our favorite terminal, let's run the script buildwith the command:

npm run build

The folder my-app/appwill be created and inside it we will have the index.jscompiled file :

my-app
├── app <-- folder generated by babel
│ └── index.js <-- compiled file
├── app-src
│ └── index.js
└── package

The command will result in the file my-app/app/index.js, identical to the original file in my-app/app-src/index.js. They are identical because we have not yet used any features that Babel offers us through presets or plugins , it is time to install them.

When we use a compiler like Babel, it’s the generated scripts we load in our browser or our Node.js application, so we say the application depends on a build step.

@ babel / preset-env

The first module we will install is @babel/preset-env. It is a special module that will compile our code for an earlier version of ECMASCRIPT if the feature we are using is not supported by market browsers.

Let’s install it:

npm install -S @babel/preset-env

It is not enough to install it, we need to configure Babel to take into account the module and we do it through the file my-app/.babelrc:

// my-app/.babelrc
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": ["last 2 versions"]
}
}]
],
}

All presets prefixed with ES20xx have been discontinued, and @ babel / preset-env is required .

The previous code adds @babel/preset-envas preset used by Babel by setting it at the same time. With this setting, only features not yet implemented in the last two versions of browsers will be transcompiled into compatible code.

This preset is based on compatibility information posted at https://github.com/kangax/compat-table

Now that we have the preset set up, let’s take a leap into the future and use features that have been proposed to TC39, the committee that governs the future of the ECMASCRIPT specification.

Installing plugins

There are a number of plugins created exclusively for Babel. For testing purposes, we will install two of them that implement proposals that will still come into the language, they are:

  • @ babel / plugin-proposal-pipeline-operator
  • @ babel / plugin-proposal-optional-chaining

Let’s download both plugins at once:

npm install -S @babel/plugin-proposal-pipeline-operator @babel/plugin-proposal-optional-chaining

Downloading the plugins is not enough. They need to be added to the plugin list at .babelrc:

// my-app/.babelrc
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": ["last 2 versions"]
}
}]
],
"plugins": [
"@babel/plugin-proposal-pipeline-operator",
"@babel/plugin-proposal-optional-chaining"
]
}

Now that we have everything in place, we’ll take a look at the features offered by them.

@ babel / plugin-proposal-pipeline-operator

The pipeline operator is essentially a syntactic sugar for single-argument functions that are chained.

Let’s change by my-app/app-src/index.jsadding the following code:

After executing the command npm run buildthe file my-app/app/index.jswill have this structure:

Although structurally different from the original file, it is code that will work in current browsers and the Node.js platform.

@ babel / plugin-proposal-optional-chaining

We have the following code that accesses the property of an associated object.

Excellent, but if the property singer does not exist? We can shield you with the following trick:

However, using optional-chainingcan simplify our code to:

After compiling the file, the end result will be:

A note about Babel and TypeScript

Although TypeScript may historically (when configured) compile code written in ES2015 (ES6) to ES5 and support some ES2017 (ES8) features such as async / await , its focus is not on compiling features under development or newly added in JavaScript specification that requires implementation in market browsers or the Node.js platform. In this sense, Babel is much freer to implement these features.

The good news is that from the TypeScript team’s own contribution to the Babylon parser used by Babel and the preset babel-preset-typescript , it will be possible to use the full power of Babel with this language. Programmers in the TypeScript language can anticipate the future and use more modern JavaScript features.

Conclusion

With the help of Babel we can use the latest in JavaScript without having to wait for support to reach browsers or even the Node.js platform. Now, with the Babylon parser supporting TypeScript, programmers in this language will also be able to benefit from Babel.

Is that you? Already use Babel? Share your experience with us.

--

--

Ashan Dhananjaya

Versatile Full-stack Developer with 4+ years of experience designing, developing, and managing complex applications and internal frameworks.