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 −
Here is the project structure that we created.
Now to work with Babel we need to instal Babel cli, Babel preset, Babel core as shown below −
Execute the following command to install babel-cli −
npm install --save-dev babel-cli
Execute the following command to install babel-preset −
npm install --save-dev babel-preset-env
Execute the following command to install babel-core −
npm install --save-dev 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 −
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 −
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 −
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.
To execute to es2015, following command is used −
npx babel index.js
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
Here is the file that we created, index_es5.js −