DEV Community

Cover image for Get started with ES6 JavaScript for writing Node.js using Express
Olushola O.
Olushola O.

Posted on

Get started with ES6 JavaScript for writing Node.js using Express

Have you ever tried writing ES6 JavaScript for frontend applications, and it caught your fancy, and you do not want to stop, but got into backend development using Node.js, and you had to go back to the old-fashioned ES5 syntax? Well, in this article, I will guide you on how to set up an ES6 transpiler for writing ES6 codes on the server-side using node.js and babel.

What is ES6 ?

ES6 refers to version 6 of the ECMA Script programming language. ECMA Script is the standardized name for JavaScript, and version 6 is the next version after version 5, released in 2011. It is a significant enhancement to the JavaScript language and adds many more features to simplify large-scale software development.
Find out more here

What is Babel?

Babel is a toolchain mainly used to convert ECMAScript 2015+(ES6+) code into a backwards-compatible version of JavaScript in current and older browsers or environments.

This also means that you can use Babel to convert our ES6 codes for backward compatibility when writing node.js applications.

A normal ES5 code snippet for importing express will look like this...

var express = require('express')
Enter fullscreen mode Exit fullscreen mode

When using ES6 syntax, all you need to do is just import your package like this

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

When writing this article, you can use some ES6 JavaScript syntax in your node.js project, but not all are supported yet. We will proceed to set up our node.js application to use ES6+ syntax.

I assume you have prior knowledge of writing JavaScript/node.js applications.

Let's get our hands dirty🤸

If you do not have Node.js installed, you can download it from the Node.js website.

We will use NPM as our package manager, and you can use yarn if you prefer.

Create a new folder, open it in your preferred command line, and proceed with the following steps.

Type npm init on your command line and follow the prompt.

This helps to initialize a new node project and install the necessary packages for our application.

Next, we installed the necessary packages to set up our application for writing Es6 JavaScript codes.

Enter the following commands in your CMD to install Babel and its dependencies. As stated above, Babel is the transpiler needed to compile our ES6 codes to ES5.

Install packages:

npm i @babel/cli @babel/core @babel/node @babel/preset-env --save-dev
Enter fullscreen mode Exit fullscreen mode
npm i @babel/plugin-proposal-class-properties @babel/plugin-proposal-object-rest-spread --save-dev
Enter fullscreen mode Exit fullscreen mode
npm i rimraf nodemon --save-dev
Enter fullscreen mode Exit fullscreen mode

Once you install all the packages, open the folder using your preferred editor if you have not done that earlier.

We will edit the package.json file to continue the setup for running our application and build the code for deployment on any hosting platform. We will update the script's section of our package.json file to complete the setup.

Here is what it should look like 👇

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "rimraf dist && babel src --out-dir dist  --copy-files",
    "start": "node dist/app.js",
    "start:dev": "nodemon --exec babel-node src/app.js"
  },
Enter fullscreen mode Exit fullscreen mode

Explaining the scripts properties

  • build: This command creates our ES6 codes using babel and dumps the output inside the dist directory (automatically deleted and recreated on every build). The dist directory contains the duplicate files and folder in our base directory. The only difference is that it includes codes transpiled from ES6 to ES5.

  • start: This command starts our node.js application after converting it to ES5 codes inside the dist directory.

  • start:dev: This command starts our application using nodemon(it helps to restart our server automatically when any JavaScript file changes) and converts all ES6 codes in-memory to ES5 using babel-node. You do not want to do this in production. That is why we have the build command for more optimized performance.

Next, we create a .babelrc file in the root directory of our application, this file is used to add configurations for our babel package in order to work correctly.
Copy the code below into the file

{
  "presets": [
    ["@babel/env", {
      "targets": {
        "node": "current"
      }
    }]
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Follow this link to learn more about using babel.

Furthermore, let us create a basic express application to display an array of items using the ES6 syntax.

1. Install express

npm i express --save
Enter fullscreen mode Exit fullscreen mode

2. Create a new folder called src in your project's root directory
create an app.js file inside the src folder and copy the codes below inside the file you just created

import express, { json } from 'express';

const app = express();

app.use(json())

const PORT = process.env.PORT || 3000;

app.get('/', async (req, res) => {
    res.json({ status: true, message: "Our node.js app works" })
});

app.listen(PORT, () => console.log(`App listening at port ${PORT}`));

Enter fullscreen mode Exit fullscreen mode

3. Run your development server

npm run start:dev
Enter fullscreen mode Exit fullscreen mode

You should have something like this
Screenshot of cmd starting development server

Go to http://localhost:3000 on your browser, and you should see a JSON response displayed.

4. Create an items.js file in the src folder
paste the following code below inside the file.

const items = [
    {
        id: 1,
        username: "John doe",
        cartItems: ['football', 'ps5', 'cd-rom'],
    },
    {
        id: 2,
        username: "Jane doe",
        cartItems: ['mobile phone', 'game pad'],
    }
];

export default items;
Enter fullscreen mode Exit fullscreen mode

Notice we used export default instead of module.exports, we can do this thanks to the ES6 syntax for writing JavaScript.
Save the file and watch your server restart automatically.

5. Import items module inside your app.js
Import your custom module inside app.js and return it from a GET route /items, your code should look like this

import express, { json } from 'express';
import items from './items';

const app = express();

app.use(json())

const PORT = process.env.PORT || 3000;

app.get('/', async (req, res) => {
    res.json({ status: true, message: "Our node.js app works" })
});

app.get('/items', (req, res) => {
    res.json({ status: true, message: "Fetched all items", data: items })
})

app.listen(PORT, () => console.log(`App listening at port ${PORT}`));
Enter fullscreen mode Exit fullscreen mode

That's it, we are done, now save all files and your server should restart automatically.

Open your browser, then go to http://localhost:3000/items, you should see a success response with all your items displayed.
Image showing all items from our REST-API response

If you encountered any issues, make sure you followed all the steps correctly or comment below, and I will definitely reply you.
You can expand this project using your desired architecture, web framework, e.g. Fastify, or even integrating a database, it is solely up to you.


Conclusion

This article taught you how to write ES6 node applications using babel for backward compatibility. You can find the codebase for this article on GitHub, follow this link, don't forget to follow me 👀

Watch out for my article on getting started with writing Typescript for your node.js application.

I hope you found this helpful, Chao ❤️

Top comments (14)

Collapse
 
0xaskar profile image
Askar

Good and easy to follow content. I think it would be useful to just include for users, how to make a post route. Odds are some people would be confused about that.

Collapse
 
geekygeeky profile image
Olushola O.

Thanks for the feedback, I will work on that, great idea.

Collapse
 
diyachou profile image
Diya Choudhury

we can just add "type": "module" in the package.json and it will work, or am i wrong?

Collapse
 
geekygeeky profile image
Olushola O. • Edited

Hi Diya, you won't enjoy the full benefits of ES6 if you use "type":"module" in your package.json file, that is why Babel was used in this tutorial :)

Collapse
 
dtes profile image
dtes

Nice

Collapse
 
geekygeeky profile image
Olushola O.

Thanks for the feedback :)

Collapse
 
devwraithe profile image
Ibrahim Ibrahim

Nice write up! It's really helpful 👏

Collapse
 
geekygeeky profile image
Olushola O.

Thanks for the feedback :)
Much appreciated

Collapse
 
jobic10 profile image
Owonubi Job Sunday

This is 🔥
Well written 🚀

Collapse
 
geekygeeky profile image
Olushola O.

Thanks so much boss. Always an honour 🙇‍♂️🙇‍♂️

Collapse
 
ahmadinjo profile image
Ahmad Busari

Great article. Simple and straightforward.
Thanks for this

Collapse
 
geekygeeky profile image
Olushola O.

Thanks for the feedback.
Much appreciated

Collapse
 
iammastercraft profile image
Boluwaji Akinsefunmi

Thanks for shedding light on this 🤲🏽

Collapse
 
geekygeeky profile image
Olushola O.

Thanks for the feedback boss 🙇‍♂️🙇‍♂️