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:
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.
Guide to migrate from babel-node to node
Overview
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.
Getting started
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.
"clean": "rm -rf build && mkdir build",
- Add a npm script to transpile the server files eg.
"build-server": "babel -d ./build ./server -s"
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.
"build": "npm run clean && npm run build-css && npm run build-server"
- Set a start script pointing to the build directory eg.
"start": "node ./build/index.js"
Debugging
If you want to debug the NodeJS app using node-inspector then add the debug option to the npm start script. eg.
"start": "node --debug ./build/index.js",
Example
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
Running Unit Tests
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.
Running an app in develepment
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.
Play with ESNext on CLI/REPL
I also use babel-node as REPL on the CLI all the time to try out ES6 features like Maps, Sets, const, destructuring, etc.