DEV Community

Cover image for Configure Babel for a Nodejs Application
Adebayo Ilerioluwa
Adebayo Ilerioluwa

Posted on • Edited on

Configure Babel for a Nodejs Application

Introduction

What is Babel

From the official babel 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 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 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

npm init -y
Enter fullscreen mode Exit fullscreen mode

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 a web framework for Node.js and nodemon a tool used to automatically restart Node.js applications when file changes are detected.
Open your terminal and add the following snippets

npm install --save express
npm install --save-dev nodemon 

Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode
npm install --save-dev  @babel/node @babel/preset-env @babel/plugin-transform-runtime @babel/runtime @babel/polyfill

Enter fullscreen mode Exit fullscreen mode

@babel/core - a fundamental package to run any babel setup/configuration.

@babel/cli - A built-in CLI which can be used to compile files from the command line/terminal.

@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- 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 - A plugin that enables the re-use of Babel's injected helper code to save on code size.

@babel/runtime - 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


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

Enter fullscreen mode Exit fullscreen mode

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.

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");
});

Enter fullscreen mode Exit fullscreen mode

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.

 "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"
  }

Enter fullscreen mode Exit fullscreen mode

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

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

Top comments (7)

Collapse
 
mmostafavi profile image
Mahdi Mostafavi • Edited

Please Fix the typo in .bablerc configuration.

instead of "plugins": ["@babel/transform-runtime"]
one should use "plugins": ["@babel/plugin-transform-runtime"]

Collapse
 
blackheart1520 profile image
Hieu Dong

Nice article, I just wonder if the vscode's intellisense supported this?

Collapse
 
adebayoileri profile image
Adebayo Ilerioluwa

Thanks for feedback Hieu, Vscode intellisense supports the setup.

Collapse
 
igoreliasm profile image
Igor Elias

Nice article.
Great to see it

Collapse
 
saxenanickk profile image
Nikhil Saxena

Nice πŸ‘

I was looking for these scripts only.

Collapse
 
adebayoileri profile image
Adebayo Ilerioluwa • Edited

Happy to help Nixhil. πŸ‘

Collapse
 
satheshrgs profile image
Sathesh Rgs

Do we need @babel /polyfill ?