Getting started with Babel and Node
However, ES6 is not widely supported by all browsers especially older ones which poses a challenge.
‘Oh okay, then how do I take advantage of the spicy ES6 features and still support all browsers?’
Babel’s got our backs!
The focus of this post is to highlight the steps necessary to quickly get started with Babel on a Node project. Let’s dive in, shall we?
Step #1: Installation
As mentioned earlier, Babel is a node module. This means the first step to getting started is to install it in your project:
npm install --save babel-cli
The above command updates your package.json file with the new dependency.
Step #2: Build
Installing Babel alone will make no difference in your project. To actually get Babel doing its work which is to transpile your files to ES5, it is necessary to define a build script in your package.json file to fire Babel up.
"build":babel ./server/ -d dist/server
In other words, you are saying to Babel: Hey, I need you to convert all the files you find in a server folder into a dist/server folder
Voila, Babel does this and you will notice a new ‘/dist’ folder in your project directory which is a transpiled version of your original files.
Step #3: Update Start Script
To run the resulting files from the Babel transpiling process above, let’s modify our start script:
“start”: “babel-node server/app.js
Step #4: Create a gitignore file
The .gitignore file tells the version control system you are working with what files or folders you do not want pushed or made public. Let us add this to our .gitignore file which should be created in the root of our project:
With these steps, you should be able to use a syntax such as ‘import’ instead of ‘require’ without getting an error. Running ‘npm start’ should also give a similar output to this in our terminal:
Server running on port 3000
You can find out more interesting features of Babel from the official documentation
Thanks for reading.