Using ES6 for your Node.js Application running on Express, using Babel

Tushar Tuteja
JavaScript in Plain English
3 min readDec 6, 2019

--

We all love ES6 syntax, and we have been using it in our front-end applications build on react and other frameworks.
It would be nice to be able to use ES6 syntax for our backend nodejs application.
It is very easy to set up and pretty straightforward. We’ll use an exiting project created using express-generator and then would add babel compiler to use es6 syntax.

What is babel? It is a compiler that would compile our es6 code into nodejs understandable code. For more information on babel go to https://babeljs.io/

For those who directly want to see code, go here https://github.com/tushartuteja/es6-sample-babel-nodejs

We’ll do the following things.

  1. We’ll create a backend application using express-generator.
  2. Add babel dependencies and .babelrc file.
  3. Modify package.json to see if everything works.
  4. Change one file into es6 syntax.

Part 1: Creating a sample application

We’ll use the following commands. Screenshot to follow.

express sampleApp
cd sampleApp
npm install
npm start
Generating a sample app using express generator
Running npm install and npm start
A sample application running default route ‘/’

Part 2: Adding babel to it.

We’ll add babel as dev dependencies, We need to add three package to our project.

npm install --save-dev babel-cli babel-preset-env rimraf

We have added the following packages

  1. babel-cli a command line tool to use babel.
  2. babel-preset-env a preset to use. A set of rules for babel to compile our code.
  3. rimraf: a pakcage to clear our dist folder.

Now need to create a new file .babelrc, it contains the following

{"presets": ["env"]}

Part 3: Modifying package.json

Have added a build script and a start script

Start script now first builds the project, and then runs the same command (bin/www) but out of dist folder, dist is basically short for distrubution. The code that would be distributed(deployed).

Build scrips first clears the dist folder(any stale files) then uses babel to compile the whole code.

Now let’s check if the project still works.

Running npm start after adding babel to the project.
Still works, we didn’t break anything.

Part 4: Modifying an existing file(index.js)

The file looks like the following and is required inside of app.js, attaching both the files.

Now let’s modify index.js file.

Modified file using ES6 syntax.

Have use import statement and export default router statement, rest of the code is same. This is our es6 syntax here.

In app.js we have done the following changes:

import index from './routes/index';app.use('/', index);

Earlier these lines were:

var indexRouter = require('./routes/index');app.use('/', indexRouter);

Let’s check if our es6 syntax works or now.

Voila, it works!

--

--