How to use babel for production

babel-node not meant for production use

I got to the point where my apps had to ship to production, and read in the latter article as well as in Babeljs CLI documentation the following:

Image for post
Image for post

You should not be using babel-node in production. It is unnecessarily heavy, with high memory usage due to the cache being stored in memory. You will also always experience a startup performance penalty as the entire app needs to be compiled on the fly.

Before I read that I was running my apps with babel-node.

npm start script

Guide to migrate from babel-node to node

Warning, this was written for Babel v5+

To code NodeJS apps using ES6(and/or Javascript Next) we have to transpile it first with babel and run it with node instead of running it directly with babel-node.

First, move all the server NodeJS files into a directory eg. server. Consider that babel will need an output directory.

Then work in package.json to do the following:

  • Set a npm script to clean/create the build directory eg.
  • Add a npm script to transpile the server files eg.

The -d option is for out-put dir and the -s option is to enable the source maps (handy when debuggin with node-inspector)

  • Set build-server script to run from the build script eg.
  • Set a start script pointing to the build directory eg.

If you want to debug the NodeJS app using node-inspector then add the debug option to the npm start script. eg.

Here is an example of how your scripts in package.json could look like after following this guide.

Thoughts on when to use babel-node

babel-node is good for:

  • running unit tests
  • running an app in development
  • run CLI/REPL to play with ESNext methods

As you can see in the example npm scripts above, I use babel-node to run unit tests. So you don’t have to transpile before running tests.

If you’re using a watcher or if you want to restart faster while developing, babel-node might be best for you to run while developing.

I also use babel-node as REPL on the CLI all the time to try out ES6 features like Maps, Sets, const, destructuring, etc.

Image for post
Image for post

Written by

I share my findings at https://twitter.com/Cuadraman

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store