Using ES6 for your Node.js Application running on Express, using Babel
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.
For those who directly want to see code, go here https://github.com/tushartuteja/es6-sample-babel-nodejs
We’ll do the following things.
- We’ll create a backend application using express-generator.
- Add babel dependencies and .babelrc file.
- Modify package.json to see if everything works.
- Change one file into es6 syntax.
Part 1: Creating a sample application
We’ll use the following commands. Screenshot to follow.
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
- babel-cli a command line tool to use babel.
- babel-preset-env a preset to use. A set of rules for babel to compile our code.
- rimraf: a pakcage to clear our dist folder.
Now need to create a new file .babelrc, it contains the following
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.
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.
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!