• How to use babel for production babel-node not meant for production use

    • 1934
    • admin

    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.

    npm start script

    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.