BabelJs – CLI


BabelJS – CLI


”;


Babel comes with a built-in command line interface, which can be used to compile the code.

Create a directory wherein you would be working. Here, we have created directory called babelproject. Let us make use of nodejs to create the project details.

We have used npm init to create the project as shown below −

Npm Init

Here is the project structure that we created.

Project Structure

Now to work with Babel we need to instal Babel cli, Babel preset, Babel core as shown below −

babel-cli

Execute the following command to install babel-cli −

npm install --save-dev babel-cli

Babel Cli

babel-preset

Execute the following command to install babel-preset −

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

Babel Preset

babel-core

Execute the following command to install babel-core −

npm install --save-dev babel-core

Babel Core

After installation, here are the details available in package.json −

We have installed babel plugins local to the project. This is done so that we can use babel differently on our projects based on the project requirements and also different versions of babeljs. Package.json gives the version details of babeljs used.

In order to make use of babel in our project, we need to specify the same in package.json as follows −

Package Json

Babel is mainly used to compile JavaScript code, which will have backward compatibility. Now, we will write our code in ES6 -> ES5 or ES7 -> ES5 also ES7->ES6, etc.

To provide instructions to Babel on the same, while executing, we need to create a file called .babelrc in the root folder. It contains a json object with details of the presets as shown below −

Json Object

We will create the JavaScript file index.js and compile it to es2015 using Babel. Before that, we need to install the es2015 preset as follows −

Install es2015

In index.js, we have created a function using the arrow function which is a new feature added in es6. Using Babel, we will compile the code to es5.

Js_Index

To execute to es2015, following command is used −

npx babel index.js

Output

es2015 Output

It displays the index.js code in es5 as shown above.

We can store the output in the file by executing the command as shown below −

npx babel index.js --out-file index_es5.js

Output

Execute

Here is the file that we created, index_es5.js −

Created Index

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *