Node server with ES6

Today I was wondering how could I write ES6 code and run it on node so I could write my applications using always the same pattern, no matter if I’m writing Node backend code of React Front-end code.

As a matter of fact, it’s quite simple to convert your node applications to full ES6 using Babel. You just have to add some modules and change some configurations.

First of all, you need to install Babel. We’ll install Babel in the development dependencies since we won’t use it in production. You can do that using the command below:

npm i -D @babel/cli @babel/core @babel/node @babel/preset-env @babel/register

I also needed to install another babel related package in the dependencies, this time in the main dependencies:

npm i @babel/polyfill

You also have to create the Babel configuration file:

$ touch .babelrc

And add this configuration to it:

{
"presets": ["@babel/preset-env"]
}

To keep everything organized, I moved my app into a folder called src. That way we can have all the source code and final compiled code into separated folders. I also added some scripts to my package.json to run the build and run the server in development mode using nodemon.

There’s one more thing to change. I just could not use the bin/www script to run the server, so I just copied the file to the src folder and renamed it to server.js.

"scripts": {
"build": "babel src -d dist",
"start": "nodemon src/server.js --exec babel-node",
"test": "echo \"Error: no test specified\" && exit 1"
}

The build script runs babel and compiles all the files inside of src folder and saves them to dist folder.

The start script runs the server.js file inside src folder passing code thru babel-node to transpile it. This way you can test the code on src folder in real time. Every time you save a file it will recompile and restart the server.

One more thing, if you are using sequelize, it’s best to add another file to the root folder of your application with some sequelize configuration. That’s important because we have moved the source code of the application to the src folder.

Just create a file called .sequelizerc and add the following code to it:

require("@babel/register");
const path = require('path');

module.exports = {
'config': path.resolve('config', 'config.json'),
'models-path': path.resolve('src/models'),
'seeders-path': path.resolve('src/seeders'),
'migrations-path': path.resolve('src/migrations')
}

Now you just have to convert all of your code to ES6. The conversion is the easy part, you can start by changing all the require calls to import and all the module.exports do export.

If you want to take a look at the boilerplate, check out at github:

https://github.com/rcabarreto/nodeServerES6

Leave a comment

Leave a Reply