Codementor Events

Easy set up: Babel 7 for Nodejs

Published Jan 22, 2019Last updated Jan 23, 2019
Easy set up: Babel 7 for Nodejs

First things first, why babel? We use babel if our JavaScript code is written in ES6. Currently, node is unable to read certain syntaxes of ES6, so in order for node to successfuly run our script, we require some sort of package (in this case, babel), that will help transpile all our ES6 code to ES5.

Why not just write the code in ES5? I know we might be thinking this, and yes, you can write the code in ES5 to avoid all the extra hassle. But as we also know, programming languages are always evolving, and it's best practice to stay current with changes, so that way, our skills evolve as development occurs. So regardless of the nature (ES5 / ES6 / ES7^) of the project we get, we are well equipped and prepared to brace the challenges.

P.S: This tutorial is based on setting up babel in development mode and not production mode.

Okay, now that we have all that out of the way, let's get into it;

Step One
I am going to go ahead and assume that at this stage we have some ES6 code to work with, meaning that we have node installed, package.json, and server side index.js (entry file) ready to go. if you don't have the setup mentioned, then, I believe that this turtorial would be helpful Node/Express API tutorial

First thing we want to do is install the packages listed below in order to get babel up and running. We will be saving them in our dev-dependencies on installation.

  • babel-cli
  • babel-core
  • babel-node
  • babel-preset-env
npm i @babel/cli @babel/node @babel/core @babel/preset-env --save-dev

Step Two
Now that we have our packages, we want to setup the babel configuration;

  • Create a .babelrc file in the root folder of your project
  • Write the configuration below in the file you created:
{
  "presets": [
    "@babel/preset-env"
  ]
}

Step Three
This is the final step, we will be using babel-node to run our script. Your script should look like the following:

"scripts": {
    "start:server": "babel-node -- ./server/index.js",
  },

Where index.js is the entry file of our server folder (server side).

Next we want to test that it works:

npm run start:server

The command above, should have our server up and running.

That's All Folks!

I hope you found this helpful, quick and easy to follow, please feel free to ask any questions below, if any of the steps above are unclear.

Discover and read more posts from Osaze Edo - Osagie
get started
post commentsBe the first to share your opinion
Show more replies