An unpleasant babeljs experiment
We all love new technologies, and we want to use them as soon as they’re out. ES6 comes with really nice features, for example:
- arrow function
- default function argument value
- block scopes
- rest parameters
Thing is, nodejs doesn’t allow the use of all those new, and mostly nice features, yet. This is why some folks build the well known Babeljs.
Yeah, this was my reaction too at first sight. It seems flawless. Building apps with a futuristic code, trying a lot of new features. The ES6 dream has come through! On top of that a nice-looking documentation!
So, like thousands of people I tried it, used it and over used it. I build a small project using the great
...arguments, templates and so on…
The first caveat, publish…
When I wanted to publish my package to npm I hit a wall. I needed to share my pm2 module, on npm, and with tar packages.
If you want to do so, you have two solutions:
- babelize your code and publish/pack the compiled one
- use the Require hook and pollute the global scope
The most clean option is the first one, for example by using gulp-babel.
Actually it’s bad.
- You have to publish only the compiled files (either by changing the package.json, or by juggling with backup, src and dest
npm publishis not easy to test without releasing new versions that you can’t erase:
- It’s actually a lot of code, headache, time for not so much
Let’s try to use child processes
Child processes are really easy to use with nodejs. With the power of IPC and the fork method you can do a lot of fun, nice and easy stuff. If you’ve a use case, use it.
I had a use case and, as I started with babel I wanted to enjoy experimental ES6 features!
To use babeljs inside a fork you have, again, two solutions:
- use the
babel-nodeexecutable instead of the default
- use the require hook
I had trouble using the
babel-node trick, as far as I can remember it was because of IPC.
So I used the require hook (as it was used in PM2). Thing is you’ll have to add
babel to your dependencies. With a 24 Mb weight and 216 (not deduped) combined dependencies, it’s not light.
Actually with node > 4.0 and the V8 update almost every interesting feature is now available! See the list of default supported es6 features.
If you don’t yet, use
'use strict'; to support Block-scoped declarations like
class. Or the
--use_strict argument (not compatible with mocha).
--harmony flag can be useful to enable es6 staged features like
Babeljs is a nice tool to test features, just think twice before using it.