You might find yourself in a situation in which you need to use ES6
export syntax in Node. The problem is, Node doesn’t yet natively support these keywords, and you’ll be met with with a nasty error. If you catch it on a bad day, it might even have some choice words about your favorite relative.
This isn’t intended to be an in-depth introduction or deep dive into Babel and transpiling — this should help you get off the ground and working quickly. Let’s get some really simple setup out of the way. We’re going to code ourselves into a little problem, then use Babel to save the day.
Our demo starts with the following structure. Feel free to copy the code snippets below.
│ └── functions
│ └── multiplyByTwo.js
Yes, the humble basic arithmetic program. Give it a run with
Unless you decided to change
index.js, the terminal should print the number 4.
Now, let’s break it with a couple of small changes and make it work again. First, we’re going to change
multiplyByTwo.js — specifically, we’re going to utilize the
export keyword instead of
module.exports. Then, we’re going to change the
require call in
index.js to an import statement. Here’s how that should look.
Go ahead and run the program again. Take a deep breath.
Hold back the tears. Quell the urge to throw your computer across the room. We can fix this mess we’ve made together. Babel will help us.
The solution we’ll be using for now is a development solution — you shouldn’t use it for production for performance reasons.
We need to get two packages:
babel-preset-env and save them both as dev dependancies. Then, we need to create one more file called
.babelrc at the root of our project, with our babel configuration. All this file will contain is a JSON object with one key, specifying that we’re using
babel-preset-env as our preset.
Now we’re set up to transpile our code at runtime, but there are some slight changes we need to make. Specifically, we need to change how we’re running our program in the shell.
babel-cli gives us
babel-node, and that’s what we’ll be using. There are a couple of commands we can use — either one should work.
Or, we can use npx. Here’s what it does (from the documentation):
<command>either from a local
node_modules/.bin, or from a central cache, installing any packages needed in order for
That saves us the hassle of typing out the entire path the
babel-node executable and allows to simply type
npx babel-node index.js
You be greeted with the number 4, just as we were earlier.
Babel can bring a lot of power to you as a programmer, and hopefully this byte sized article can smooth out what seems (at least to me) to be a common stumbling block.