Running ES6 Codes in Node.js with Babel.js

Ryan Kim
3 min readOct 26, 2020

There is nothing we can take for granted when we use “import” in Node.js

I have confused when I built client-side with react.js, I took the “import” module for granted that I import modules. But it was a huge mistake that I often create React.js project folder with “create-react-app”.

I used the “import” module in the same way as dealing with reacts in the node.js serverside configuration, and made the following error.

I missed JS compiler, Babel.js in node.js

I missed the Babel.js setting in my node.js project and tried to solve this error ASAP.

Before I install several modules to use “import”, what’s the role of babel.js?

Babel.js

Babel is a popular tool for using the newest features of the JavaScript programming language. Developers can use new JavaScript language features by using Babel to convert their source code into versions of JavaScript that evolving browsers are able to process. ( — Wikipedia)

So, we can use the latest version of JS by setting up babel.js and it allows us to translate the latest JS into the old version.

Let’s start to install four things about babel.

What’s the role of Babel?

@babel/cli: The command line of Babel

@babel/core: The core package of Babel

@babel/node: We can use transpile & running server together with Babel-node.

@babel/preset-env: Babel settings allow you to combine multiple plug-ins on your own or use pre-prepared presets.

npm install @babel/cli @babel/core @babel/node @babel/preset-env

Then, follow the next steps.

create .babelrc and write this object in it.

and write these codes down in your package.json.

now, you can utilize “import moudle” when you execute npx babel-node index.js in your console.

By the way, I’d like to introduce one more thing, nodemon with ECMAScript.

You can just follow the steps below.

This is all.

I thought setting up babel.js and translate modern JS is quite difficult works and spent lots of time.

But it was my wrong judgment. All things I do are to learn steps about transcompiler.

Memorizing what I learned with my words is completely helpful for my next project.

Does anyone who needs my knowledge about Babel.js in this article, please refer to it and leave a comment if you have any feedback.

Ryan

Reference

Nodemon ECMAScript Setting

--

--