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';
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
- @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"
In the project's root folder, create a .babelrc;
{
"presets": [
"@babel/preset-env"
]
}
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
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/"
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
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"
},
In the next article, weβll be setting up a database for our application.
Top comments (0)