Brayan Arrieta Alfaro
Brayan Arrieta Alfaro's Blog

Brayan Arrieta Alfaro's Blog

How to use Babel in your Node.js project

How to use Babel in your Node.js project

Brayan Arrieta Alfaro

Published on Jul 16, 2021

5 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Today we will be learning about how to use Babel in your Node.js project step by step. Babel will transpile our ES2015+ code and module syntax to older-style code for compatibility purposes. During this post, I will use the basic Hello World Express API as an example and we will integrate Babel step by step.

Create the node example project

First of all, we need to create the node project directory

mkdir babel-node-example

After that, you need to enter that directory and execute the next command to initialize the project and answer all the questions related to initialization.

npm init

In the case of this example app, we will create and hello world with Express so we need to install the next dependency

 npm install express --save

Once the dependency is installed we need to create a folder called src in our project and a new file called index.js and paste the next content.

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Also, we need to add a new npm script to the project

 {
    "start": "node ./index.js"
 }

After that when we execute the command npm start and open the next URL http://localhost:3000/ once the page is loaded we will see a page with a message Hello World!

In the case that you just wants to do the babel setup, you can just clone the next repository how-to-use-babel-in-your-node-project

Install dependencies

Now we will install babel and its dependencies in our project

 npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
  • @babel/cli: It is a built-in CLI that can be used to compile files from the command line.
  • @babel/node: Is a CLI that works exactly the same as the Node.js CLI, with the added benefit of compiling with Babel presets and plugins before running it.
  • @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).
  • @babel/core: Is the Babel compiler core

Setup

.babelrc

We need to create a file called .babelrc with the next content

{
  "presets": [
    "@babel/preset-env"
  ]
}

After that, we need to change the npm script start to use Babel

{
     "start": "babel-node ./src/index.js"
}

The application will still work in the same way after that.

Migrate the code

With Babel, we can use some ECMAScript we can use several awesome features in our project. However, we need to migrate the old code to use the new ECMAScript features.

index.js

In the case of the index.js file, the change was simple just we changed the require to import which is a new feature in ECMAScript.

import express from 'express';
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Nodemon

In the case that we want that our app to update automatically after we apply a change, we can use Nodemon. We need to install as the development dependency

npm install --save-dev nodemon

Once Nodemon was installed we need to change our npm start script as

{
    "start": "nodemon --exec babel-node ./index.js",
}

After that every time that we apply a new change our application will be updated.

Production environment

Our node.js project is working for the development environment as is updating automatically with every change, in the case of the production environment we need to avoid that to had the best performance of our application. There are some other approaches to that process, however, I recommend the next one.

First of all, we need to generate a build of our application with the next script after executing the command will be created a folder called dist with the build of our application

{
    "build": "babel ./src --out-dir ./dist --source-maps",
}

We need to create an npm script to clean our build before create a new one. Basically with the next command we will delete the dist folder when is executed the command

{
    "build:clean": "rm -rf dist"
}

Also, we need to add a pre npm script to execute the command npm run build:clean before the npm run build

{
    "prebuild": "npm run build:clean"
}

Finally, to start our application from the production build we need to add the next npm script and just execute the command npm run start:prod.

{
    "start:prod": "npm run build && node ./dist/index.js",
}

The npm scripts of our project should look something similar to

{
    "start": "babel-node ./src/index.js",
    "build": "babel ./src --out-dir ./dist --source-maps",
    "build:clean": "rm -rf dist",
    "prebuild": "npm run build:clean",
    "start:prod": "npm run build && node ./dist/index.js"
},

Conclusion

JavaScript is an awesome programing language, and that’s something very healthy for web development. Every year there is a new awesome feature that can be used in the project. In this post, we have checked how to use Babel that will allow us to use the new ECMAScript feature.

Also in this repository, you can find all the code described during the post.

Let me know in the comments recommendations or something else that can be added, I will update the post based on that thanks! 👍

References

 
Share this