Setting up Babel for JavaScript very small project
I was using Webpack, TypeScript’s compiler, and now it is time to use Babel for older browsers because it is the main point of Babel.
Babel
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:
In other words, it will help us to compiled JavaScript to work in older browsers.
You can watch it too
Let’s Start
We need to install Dependencies, but on the development dependencies because Babel is for development purposes.
NPM
Initiate NPM
$ npm init -y
Install dependencies only for development purposes, we will use the babel, core, CLI and last but not least the preset-env
$ npm i --save-dev @babel/core @babel/cli @babel/preset-env
Then we need to add this command on our package JSON to run Babel, we run Babel then it will search for the src directory and finally it will compile the files on our dist directory easy right?
"babel": "babel src -d dist "
Then we need to create our JavaScript file
After that we need to add our babelrc file to add the preset and this will do the job of transform our js files for older browsers
We need to use the JSON structure to keep everything ok, then we need to add the presets in this case is the preset-env and that is all for now
Structure so far
Run command
$ npm run babel
If everything is going well we can see that it compiles our file to the dist directory
And is ready for older browsers sorry for the kindle’s example, but I really love those devices ❤ then if you want to use Babel for a specific version of the browser you need to create a browserslistrc file adding what kind of version do you want
Conclusion
Babel is a handy tool for older browsers instead of fighting with IE or another old browser you can pick this small example run your babel’s command and go for a snack and keep learning, we can specified the browser version awesome! If we work for a company who just use the Chrome version 56 or another one, really usefull!