Categories
JavaScript webpack

Installing Babel

In this blog post, you will learn how to install babel.

So what is Babel?

I like to think of babel as a translator. A translator of what? Of programming languages. For instance, newer browser are running on ES6 and above, however older browsers don’t support ES6, they support ECMAScript 2015 (ES5). So if you have a project that is coded in ES6 format, you would use babel to transpile ( convert ) your code from ES6 to ES5 so your older browsers can understand it.

Its, it’s like working with sass and css when you’re dealing with HTML.

The installation of babel will be done locally. So, we will begin by installing the following dependencies:

Babel/Core
Babel-loader
@babel/preset-env
@babel/cli

Executel the following in your terminal:

npm install -D @babel/core babel-loader @babel/preset-env @babel/cli

We’ve installed the needed dependencies, however babel does absolutely nothing out of the box. So we will need to configure it. If you check babel’s website, you will see a ton of plugins that can be used for various projects. You can check’em out here:

We will do this by creating an .babelrc file ( a hidden file within your current directory), and then place all our presents inside it.

Technically you don’t need to create a .babelrc file; as you can just configure your present within the webpack.config.js file. However, for this tutorial, we will be using the .babelrc file.

Create your file , then open it up in your favorite text editor:

touch .babelrc && <your text editor> .babelrc

Place in your presets:

{
  "presets": ["@babel/preset-env"]
}

Lets create an npm script within our package.json file; you should already have a “scripts” property in your file. If you don’t add the following and include a property for your babel script; I called mine bableBuild because I will be using the word “ build” for my webpack script:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"babelBuild": "babel src -d lib"
},
//Now, we’re ready to test babel out!!

Created a file called index.js, then open it up with your favorite text editor.

touch index.js

Enter in the follow ES6 code:

const newFunction = ((arg1, arg2, agr3) => console.log(arg1, arg2,arg3))

Save the file then start your terminal and enter the following:

npx babel <directory of your <yourIndex>.js file

Babel should have successfully transpiled your ES6 code into something older browsers can understand’ ES5.

“use strict”
var newFunction = function newFunction(arg1, arg2, agr3) {
  return console.log(arg1, arg2, arg3);
};

Let get a ‘before’ and ‘after’ look at things:

//Before transpiling:

const newFunction = ((arg1, arg2, agr3) => console.log(arg1, arg2,arg3))

//After transpiling:

“use strict”
var newFunction = function newFunction(arg1, arg2, agr3) {
  return console.log(arg1, arg2, arg3);
};

I hope you found this article helpful.