Configure Babel for a Nodejs Application
Tags: babel, node, javascript, programming
Published: 2021-01-31 13:44:33

## Introduction
### What is Babel
From the official [babel](https://babeljs.io/) documentation site, 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. Basically, Babel is a **Javascript Compiler**.

This article aims to explain and show how we can use Babel to access latest ES6 and above syntax features that are not included in recent [Node.js](http://nodejs.org/) versions. If you are interested to learn how Babel works under the hood, I would be sharing some useful resources at the last section  of the article.


##  Project Setup

### Prerequisites
Before you can get started, make sure to have an installed editor and terminal on your machine. Also, you will need an installed version of  [Node.js](http://nodejs.org/) with npm. Make sure to have everything set up before you continue to read.

We need to initialize our project with a package.json file since we are going to install some packages that are necessary for the setup

```shell
npm init -y
```
> Note: For this tutorial, we will be making use of npm as our package manager. If you are using yarn, make sure you run the corresponding command.

After successfully initializing our node project we install necessary dependencies.

First, we install [express](https://expressjs.com/)  a web framework for Node.js and [nodemon](https://github.com/remy/nodemon) a tool used to automatically restart Node.js applications when file changes are detected. 
Open your terminal and add the following snippets

```shell
npm install --save express
npm install --save-dev nodemon 

```

Next, to install packages essential for babel setup.
It's advisable to install `@babel/core  @babel/cli` as global dependencies.

```shell
npm install --save @babel/core @babel/cli

```

```shell
npm install --save-dev  @babel/node @babel/preset-env @babel/plugin-transform-runtime @babel/runtime @babel/polyfill

```

[@babel/core](https://babeljs.io/docs/en/babel-core) - a fundamental package to run any babel setup/configuration.

[@babel/cli](https://babeljs.io/docs/en/babel-cli) -  A built-in CLI which can be used to compile files from the command line/terminal.

 [@babel/node](https://babeljs.io/docs/en/babel-node) - babel-node is a CLI that works the same as the Node.js CLI, with the added benefit of compiling with Babel presets and plugins before running it.

>Note: You should not be using babel-node in production. It is unnecessarily heavy, with high memory usage due to the cache being stored in memory. You will also always experience a startup performance penalty as the entire app needs to be compiled on the fly.

 
[@babel/preset-env](https://babeljs.io/docs/en/babel-preset-env)- is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller.

[@babel/plugin-transform-runtime](https://babeljs.io/docs/en/babel-plugin-transform-runtime) - A plugin that enables the re-use of Babel's injected helper code to save on code size.

[@babel/runtime](https://babeljs.io/docs/en/babel-plugin-transform-runtime#why) - a package to be installed production dependency to avoid duplication across your compiled output.

Then, we need to create a babel config file in our project root directory `.babelrc` and write the configuration to it. feel free to add extra config to this file

```json
  
{
    "presets": ["@babel/preset-env"],
    "plugins": [
        ["@babel/plugin-transform-runtime"]
    ]
  }

```

With this done, let's create a simple Node.js/Express server. Start by creating an `app.js` file in the project root directory then add the following block of code to it.


```javascript
import express from "express";
import bodyParser from "body-parser";

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get("/", (req, res) => {
  res.status(200).json({
    message: "I am using babel in NodeJS",
    status: "success",
  });
});

const PORT = process.env.PORT || 4200;
app.listen(PORT, () => {
  console.log("server up and running");
});

```

We've come so far, Our setup is ready and it is time to run our code for babel to do its magic ✨

Open your `package.json` file and make the following modifications to the script tags.

 The `start` script will be used to compile your application code into a lower version of javascript,  node.js  understands and can be readily deployed to a node.js production server.

 The `start:dev` script can be used to run our code locally in your runtime.

 The `clean` script will be used to delete the previous builds folder when the `start` script is run.

 The `build-babel` script makes use of `@babel/cli` as explained earlier to compile code in the terminal.

 Finally, the `build` script runs both `clean` and `build-babel` commands.

```json
 "scripts": {
    "start": "npm run build && node ./build/app.js",
    "start:dev": "nodemon --exec babel-node ./app.js",
    "clean": "rm -rf build && mkdir build",
    "build-babel": "babel -d ./build ./app.js -s",
    "build": "npm run clean && npm run build-babel"
  }

```


To conclude, let's run the `start` script to make sure everything works.

After running the `start` script, a folder `build` is created in your project root directory containing the compiled `app.js` file as shown in the image.


![Screenshot (13).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612013792639/1gUWePzHO.png)

Now we can deploy our compiled application code to a node.js production server 🎉🎉. 


### Conclusion

We learnt how to configure Babel in our Node.js Project to compile latest javascript features to compatible versions for browsers and other environments.
 
If you have any questions or feedback about this article, feel free to reach out.
Thanks for reading.
 
### Useful Links

https://github.com/babel/babel
https://github.com/jamiebuilds/babel-handbook
https://github.com/jamiebuilds/the-super-tiny-compiler