What is Babel?
What is a transpiler?
Transpilers, or source-to-source compilers, are tools that read source code written in one programming language, and produce the equivalent code in another language which is in the same level.
What is transpiling then?
What is the difference between compiling & transpiling?
What is the reason for using babel?
Babel comes packaged as an node module. Installation can be done via npm.
01. first we have to install the babel-cli via
npm install –g babel-cli
02. make a project directory where you want to test babel in action. I have mine which named as “babel-example”
03. Change the directory to “Babel-example”
04. Setup the package.json by executing
npm init -y
05. Add babel into your package.json by executing
npm install –-save-dev babel-cli babel-preset-es2015
–-save-dev means we are installing these dependencies for development purpose only and we don’t want it in production. Babel-preset-es2015 is an array of plugins which allow babel to transpile ES2015 code. It includes lot of plugins like plugin for arrow function, classes & many more!!!
06. Create the .babelrc file in your root directory.
Note: This file tells the babel how we want our code to transpile. It contains a normal json. Two important properties are plugins & presets. If you just want babel to transpile specific features you can specify them with plugins property because there are separate plugins like arrow function, classes, instanceof etc & many more. But defining plugins this way is not a great idea because you want all the features of ES6 to be transpiled so instead of specifying all the plugins in plugins property babel has something called presets. There are many presets. One of them is ES2015. Presets are just a simple collection of babel plugins. That’s why we have installed babel-preset-es2015 in our example. That will allow babel to transpile all the features of ES2015.
07. Open the .babelrc file and specify es2015 preset in our presets property there.
08. Create a folder called src in our root directory and a test.js file inside it. This is the file where we are going to write our ES2015 features and we can see babel will transpile it, with the help of babel-preset-es2015. My test.js file looks like:
09. Now let’s tell the babel to convert our ES6 code into ES5 by executing
babel src -d build
src is where I have my src which has ES6 code and
buildis where i want to see the ES5 code which is formally we call it the Output or Build.
10. After running above command in terminal you will see a build folder has generated with test.js file inside it which has written the same content using ES5. My test.js file looks like :
All done ;) now we have transpiled our ES6 code into ES5 using babel. Now we know how babel works. One important thing is there are plugins for webpack, gulp, grunt etc as well.
That’s all for now, Hope you enjoyed the reading. See you again with some another hot topic!!!!.