a blog for those who code

Wednesday 24 February 2016

Getting Started with Babel - A JavaScript Compiler

In this post we will be discussing about Bable, a JavaScript compiler. It is a transpiler for JavaScript which has the ablilty to turn ES6 into code that runs in your browser today. It will help you to run features like arrows, classes , template strings, enhanced object literals to the browser which does not support it.

For example, in the below code ES6 arrow functions are changed to normal function by Babel, which means you can write and run future code today.

Babel has the greatest level of compatibility with the ES6 specification (http://kangax.github.io/compat-table/es6/) than other transpilers. It lets you use almost 70% of the new features that ES6 has. Not only ES6, Babel also tracks ES7 features.


Its good to install Babel locally i.e. project by project because different projects on the same machine can depend on different versions of Babel. So by using it locally you need to update it one at a time rather than updating it everywhere. You can install Babel CLI using the below command

npm install --save-dev babel-cli 

You also need to install Babel Preset ES2015 (babel-preset-es2015) because you need to turn on individual language features which can be done by the below command

npm install --save-dev babel-preset-es2015


To run the babel using the command line you need to execute below command, where public is the folder (all js files stored) and --presets es2015 (which presets to use).

babel public --presets es2015 

The above command will give you an output in the command line. Instead of getting the output in a command line you can also get the output as a js file for that you need to run the below command, where --out-dir is the flag of specifying output directory and compiled is the directory name

babel public --presets es2015 --out-dir compiled 


If you do not want to write the flag in your command line, you can always configure babel to do it. You can create a file named (.babelrc) and write all the configuration into that as shown below.

  "presets": ["es2015"], //presets configuration
  "babelrc": "true" // whether to use .babelrc or not

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment