Babel in Node.Js

Babel is a JavaScript compiler. It is a tool that helps you use the latest features of JavaScript programming language.

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.

Prerequisites :

  • 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 :

npm init

Set Up Babel :

Now, we will install three packages from the Babel family:

npm install --save-dev @babel/cli @babel/core @babel/preset-env
or
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:

{
"presets": [
["@babel/env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread"
]
}

Package.json Script Configurations:

"scripts": {
+ "build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
}

Conclusion

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store