DEV Community

Cover image for Stacky REST API #2 - Babel Setup
Odunayo Ogungbure
Odunayo Ogungbure

Posted on

Stacky REST API #2 - Babel Setup

Welcome to part two of building a REST API with Node.js. In the previous part, we covered the initial setup and in this part, we'll be adding babel to our project.

Babel is a tool used to convert ECMAScript 2015+ code not included in the recent Node.js versions, into a backwards-compatible version that older environment will understand.

Open up the app.js file and use javascript import statement instead of require.

import express from 'express';
Enter fullscreen mode Exit fullscreen mode

Run the application and sadly it breaks 😟!

To fix this let's set up our hero πŸ¦Έβ€β™‚οΈ Babel by installing the following dev-dependencies;

$ yarn add @babel/core @babel/preset-env @babel/node -D
Enter fullscreen mode Exit fullscreen mode
  • @babel/core - the core functionality of Babel.
  • @babel/preset-env - common bundles of plugins needed to transpile new and upcoming features.
  • @babel/node - works exactly the same as the Node.js CLI, with the added benefit of compiling with Babel presets and plugins before running it.

Edit the start script in the package.json file;

"start": "nodemon --exec babel-node src/app"
Enter fullscreen mode Exit fullscreen mode

In the project's root folder, create a .babelrc;

{
    "presets": [
        "@babel/preset-env"
    ]
}
Enter fullscreen mode Exit fullscreen mode

Run the application again and it works!

What babel is simply doing is transpiling our code to vanilla JavaScript under the hood. Anytime you use a JavaScript feature, which hasn't been introduced in Node.js, Babel makes sure that Node.js understands it so our application doesn't break.

One more important step we have to do is to build our application. In reality, we won't be using nodemon and transpiling our code at runtime when we move our application to production. Rather, we push the transpiled codes to our production server.

Install the @babel/cli module which allows us to use babel from the terminal.

$ yarn add @babel/cli -D
Enter fullscreen mode Exit fullscreen mode

Let's add a build script to our package.json file. This executes babel on the javascript files in the src folder and outputs the transpiled code to a dist folder which we can then upload to our production server.

"build": "babel src/ -d dist/"
Enter fullscreen mode Exit fullscreen mode

Build the application and we should see a dist folder in our project. You can take a look at the app.js file to see the output.

$ yarn build
Enter fullscreen mode Exit fullscreen mode

Lastly, we need to modify the scripts section in the package.json file.

"scripts": {
    "build": "babel src/ -d dist/",
    "dev": "nodemon --exec babel-node src/app",
    "start": "node dist/app"
},
Enter fullscreen mode Exit fullscreen mode

In the next article, we’ll be setting up a database for our application.

Top comments (0)