Today we are going to talk about how to compile your modern java-script syntax to browser / chrome / environment friendly executable code. Before we proceed lets first understand a few things.
It allows you to implement complex features on web pages or nowadays on server/back-end with the help of NodeJs.
Short intro to ES6
ECMAScript 6, also known as ECMAScript 2015, is a significant update to the language since ES5 was standardized in 2009. The 6th edition syntax includes classes and modules, for/of loops, arrow functions, promises and much more.
What is Babel?
Here are the main things Babel can do for you
- Transform syntax, Polyfill features that are missing in your target environment (through @babel/polyfill)
- Source code transformations (codemods)
Compile ES6+ back to ES5
- After compilation we can easily execute the code using Node.Js or any of the modern browsers.
Lets see this in action using an example.
Things to keep handy before you begin: VS-Code, Node.Js, Babel.
Let's start with initializing a new node project.
To create a blank package.json just simply press Enter all the way through. (or you can fill with the title and other info of your choice.)
The most forward way to use Babel is via the command line interface (‘CLI’). Developers recommend installingBabel locally project by project. Just simply run:
npm install babel-cli babel --save-dev
We will now update the package.json file with new “script.” instead of running Babel directly from the command line. To do so edit the “scripts” field to your package.json by putting the Babel command inside there as build.
Now Babel is installed, and we have to configure it. Create a .babelrc config file in your project root folder and enable the env preset plugin, which makes transforms for ES2015+. Install it with:
npm install babel-preset-env babel-preset-stage-2 --save-dev
To enable the preset plugin, you have to define it in .babelrc like this:
The Babel build command assumes you have src and output folder. The src folder will hold the input you want to transpile, and the output folder will contain the transpiler output. At the end your package.json file should look like this:
Now you can run Babel with the following command:
npm run build
In this sample we’ll see how to convert a simple class to ES5. Create a Rectangle.js file in the src folder including the following code:
To build your ES5 file simply run:
npm run build
Testing your output file:
In order to test your generated file, follow these steps:
- Create a new .js file and write the following codes in it.
Considering you named your file as execute.js execute the below command to see it running.
I hope you enjoyed compiling your ES6 code to ES5. Thank you!