Learn to Code via Tutorials on Repl.it!

← Back to all posts
JavaScript Tutorial > ES6 ===> ES5 with Babel!
ItamarCohen28 (10)

What's Babel?

So, I'm glad you asked! Babel is a package that transpiles ES6 code into ES5!


Why do we need Babel?

Well, that's a good question!
Some browsers aren't supporting ES6, so we want to transpile our pre made code into ES5, you can to this either manually, or with babel.
Babel isn't necessary, but it's helpful for long codes.
Let's begin!


The first function we're going to use is:
npm init
It will create for us a package.json file that will allow us to run and setup our babel.
(It will ask you for parameters, don't change anything except the description and author parameters).


Now create your JavaScript file inside a src folder.


Now install babel using this to shell scripts:
npm install babel-cli -D
There's not that much to say about this scripts, they are just installing the babel.
That's the second script that you need to run:
npm install babel-preset-env -D


Now just click on New File in your editor, and name it .babelrc.
Inside the .babelrc paste this lines of code:

{
  "presets": ["env"]
}

Now in your package.json file, in the script object, add a , to your test line at the end, and add this line of code after pressing enter.
"build": "babel src -d lib"


You're done!
Now every time you want to transpile the file into ES5 you just need to type npm run build.
@ItamarCohen28

edit: To run your files just type in the shell node ./src/index.js or node ./lib/index.js for your transpiled file
note: you can transpile newer versions of JavaScript that are above ES5 and not below!