Node.js Tip - Minimal Babel with Node v6

Written by juraci.vieira | Published 2016/11/14
Tech Story Tags: javascript | es6 | babeljs | nodejs | software-development

TLDRvia the TL;DR App

TL;DR if you happen to be using Node v6 LTS you should consider replacing babel-preset-es2015 with babel-preset-node6 for minimal transpiler effort and more use of Node’s v6 native support to ES6/ES2015.

ES 2015 and Babel

It is common knowledge on the JS community that the ES2015 was the most extensive update that the language received since its creation. It brought long waited features like variables that are scoped to the running execution context, default parameters and promises to name but a few.

Babel came to enable developers to use all the cool ES2015 updates in the browser and in Node.js as if the specification was already 100% supported. Roughly speaking they accomplished that by transforming new JavaScript into old JavaScript through the use of presets.

Node v6 LTS

As a year or so went by, Node.js updates gradually added native support to ES2015 features, Node v6 LTS was recently released and it supports 97% of ES2015 as you can see here.

Unfortunately the ES2015 import and export module syntax are among the features left out of Node v6.

So if you want to write 100% ES2015 compliant code in Node v6 you still need Babel. What you don’t need is to let Babel transform your code to old ES5, hence babel-preset-node6.

preset-es2015 vs preset-node6 comparison

Here is a simple comparison of the transformation results using those two different presets.

Given as baseline a basic express route definition using some ES2015 features:

When using Babel official preset-es2015 the resulting code will be:

//.babelrc{“presets”: [“es2015”]}

As you can see the preset transformed the code into old ES5 without taking any advantages of the native support from Node v6.

When using unofficial babel-preset-node6 the resulting code will be:

// .babelrc{“presets”: [“node6”]}

The resulting code this time takes advantage of features that are natively supported by Node v6. Only the parts not supported by Node v6 were transformed like the module imports and exports.

This small sample might not seem to be meaningful enough but at a real production scale app it’s better to work with V8 than around it. In the words of the plugin creator “The end result is nearly always a faster build and script execution timeLee Benson.

Conclusion

Babel is an amazing tool that allows us to take advantages of the updates in the language right away, but it’s healthy to review which portions of the presets you actually need, you might avoid unnecessary build times and take more advantages of Node.js native implementations.

Personally in my apps I will strive for a balance between what new JavaScript features I really want to use and a minimal amount of Babel presets to keep things running, hence the Minimal Babel title.


Published by HackerNoon on 2016/11/14