How to setup babel without Nodemon in NodeJS

In this article we are going to look at how to transpile ES6+ to ES5 in NodeJS by using babel without Nodemon.

If you don’t yet have a basic setup of a NodeJS project, then no worries. We take you through the process with easily followed steps here.

I’ve seen a lot of tutorials on how to setup babel for NodeJS using nodemon, but none without it. Therefore I decided to make this article.

What if you don’t want to install and run nodemon. What if you just need your program to end after it’s finished all of its tasks? You won’t be able to accomplish that with nodemon. The solution is rather quite simple, follow along.

Our basic setup

In our example we have our utils file with a simple function called hello, that prints to the console “Hello 👋 “. Then we have an index file that requires the utils and runs the function hello.

utils.js
index.js

We can run the files with no problem using:

node index.js

But what if we want to use the ES6 import syntax instead of the require that we used so far. We have to refactor our code to ES6 and then transpile it with babel to ES5.

Refactoring our files to ES6

ES6 utils.js
ES6 index.js

After we refactored our code we try to run the program, but we get the following error:

See also  What's TDD and how to setup jest in nodeJS

We have to transpile our code to ES5, afterwards then we can run it.

Transpiling our code to ES5

In order to do so we have to install these babel libraries.

npm i @babel/cli @babel/core @babel/preset-env

Now we have to create a new file called babel.config.js in the root folder and copy this:

module.exports = {
  presets: [["@babel/preset-env", { targets: { node: "current" } }]],
};

Then put all the files we want to compile with babel to src folder. Otherwise it will compile everything even our node_modules files folder, which we definitely don’t want.

Add these commands to package.json under “scripts“.

"transpile": "babel src --out-dir dist",
"start": "node ./dist/index.js"

And run the babel transpile command.

npm run transpile

In the end your package.json and folder structure should look like this:

Now we can run the transpiled files in dist folder with the node command using our start script.

npm start

And we are done, we have successfully compiled our ES6 JS files to ES5 to the folder dist and ran our code. 🚀💪

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *