Why use Babel in Node.js?
Node cannot use ES6 import and export statements and other cool features of ES6 syntax without using a compiler like Babel.
- Basic knowledge of Node.js
- Node installed on your machine
- Any code or text editor of your choice
Let’s go :
Let’s initialize and create a package.json file :
Set Up Babel :
Now, we will install three packages from the Babel family:
npm install --save-dev @babel/cli @babel/core @babel/preset-env
yarn add @babel/cli @babel/core @babel/preset-env -D
So once you’re done with the installation, create a new file called .babelrc for configuring babel.
This file will host all of the options we want to add to Babel. So for now, let’s use the setup which I normally use for development in my app. You can copy it and add to yours:
Package.json Script Configurations:
+ "build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
In this tutorial, we’ve learned how to use the awesome ES6 syntax in our Node app using Babel.
Note that you can add more configurations in your .babelrc file. It is not limited to what we have in this tutorial — so feel free to tweak or change it.