What is Babel, and when should one use Babel?

By: (plus.google.com) +David Herron; Date: February 25, 2018

Tags: Node.JS » JavaScript

Fast advances in the JavaScript language mean the new features are not evenly distributed. Fortunately the JavaScript language is flexible enough that in many cases new features can be retrofitted by using a polyfill among other techniques. One of those techniques is Babel, a so-called Transpiler that can convert code using new features into equivalent code using old features, so that a programmer can code with the new features and still deploy to older JavaScript implementations.

The Babel transpiler ( (babeljs.io) http://babeljs.io/) is a great way to use cutting edge JavaScript features on older implementations. The word transpile means Babel rewrites JavaScript code into other JavaScript code, specifically to rewrite ES-2015 or ES-2016 features to older JavaScript code. Babel does this by converting JavaScript source to an abstract syntax tree, then manipulating that tree to rewrite the code using older JavaScript features, and then writing that tree to a JavaScript source code file.

Put another way, Babel rewrites JavaScript code into JavaScript code, applying desired transformations such as converting ES2015/2016 features into ES5 code that can run in a web browser.

Many use Babel to experiment with new JavaScript feature proposals working their way through the ECMAscript committee (TC-39). Others use Babel to use new JavaScript features in projects on JavaScript engines that do not support those features.

When should one use Babel?

The general case is: Whenever you're deploying JavaScript code to an older JavaScript platform, while desiring to use the new language features.

There's a number of variants to that general case. The new language features - async functions primarily - are so compelling that all JavaScript programmers should be itching to use them as soon as possible. While many of the new features are simple syntactic sugar that makes JavaScript a little nicer, some (like async functions) are fundamentally important because it opens a whole new way of writing JavaScript code.

Deploying newer-style code to older browsers This is an issue we've had all along, that old browsers exist and our code (whether it's HTML, CSS or JavaScript) has to accommodate the older browsers. Raise your hands if you remember buttons telling you which browsers are best for viewing each given website? And how many websites have you been locked out of due to refusing to use Internet Explorer? And how many insist on pronouncing it Internet Exploder? Okay, I got on a little tangent, but all those questions are forms of the Old Browser problem.

We just said the new JavaScript paradigm is extremely compelling, but your marketing department knows you need to support ES-5 browsers. ES5 doesn't have the new features and does that mean you're stuck unable to use the new features? In a few years the ES5 browsers will all be replaced and then finally your marketing department will finally admit it's safe to use ES2015/2016/2017 features, but by then there will be ES-2021 features that are extremely compelling.

Babel can rewrite most of the features to run on ES5 browsers today. And when ES2021 rolls around, Babel will surely still exist and will be able to rewrite those new features to run on ES2016 browsers.

Deploying newer-style code to older Node.js implementations A variant of the issue is that Node.js hasn't always supported ES2015/2016/2017 features. If your team has declared that Node.js 0.10.x is the standard to which your code must run, then you must use Babel if you're going to use the new features.

There's a feature you can use today on Node.js 9.x -- ES6 Modules -- that aren't supported by any Node.js 8.x or earlier. And to use them on 9.x even requires an option to enable the feature, because it's so experimental.

If your team really is sticking to 0.10.x it's time to have a serious talk with the Architect. These new features are really really really compelling, and Node.js 8.9.x is about 99% compatible with the ES2015/2016/2017 features -- See (node.green) http://node.green/

The big missing feature is ES6 modules and that's not compelling enough to jump through hoops just to use them. Async functions ARE compelling enough to go to the effort.

How to use Babel?

Here's a quick example. In a Node.js project directory type these commands:

$ npm install babel-cli --save
$ npm install babel-plugin-transform-es2015-modules-commonjs --save
$ npm install babel-plugin-transform-async-to-generator --save

Then create a file named .babelrc containing:

 "plugins": [

THis declares two transformations -- one rewrites ES6 modules to CommonJS/Node.js format -- the other rewrites async functions to generator functions with a helper.

You can get help with Babel: $ ./node_modules/.bin/babel -help

To transpile one file: $ ./node_modules/.bin/babel moduleName.js -o moduleName-babel.js

Babel has commands to transpile a whole directory structure, to watch the files and dynamically retranspile anything which changes, and so on.

A typical pattern is to put ES2015/2016/2017 source files in a directory named src and use Babel to transpile everything in that directory into lib. Your system would then be instructed to execute the files in lib, and it's the lib files you would distribute.

I think it's feasible to have different transpilations for different targets. Suppose your code is to run in browsers, and you're able to detect the browser features. You could transpile with one set of transpilation plugins for one set of browsers - and use another set of transpilation plugins for other browsers - and then setup the HTML to load the correct transpilation depending on the browser.

« Node.js Web Development, 4th edition, coming soon Deploying an Express app with HTTPS support in Docker using Lets Encrypt SSL »
2016 Election 2018 Elections Acer C720 Ad block Affiliate marketing Air Filters Air Quality Air Quality Monitoring AkashaCMS Amazon Amazon Kindle Amazon Web Services America Amiga and Jon Pertwee Android Anti-Fascism AntiVirus Software Apple Apple Flexgate Apple Hardware History Apple Hardware Mistakes Apple iPhone Apple iPhone Hardware April 1st Arduino ARM Compilation Artificial Intelligence Astronomy Astrophotography Asynchronous Programming Authoritarianism Automated Social Posting AWS DynamoDB AWS Lambda Ayo.JS Bells Law Big Brother Big Data Big Finish Big Science Bitcoin Mining Black Holes Blade Runner Blockchain Blogger Blogging Books Botnets Cassette Tapes Cellphones China China Manufacturing Christopher Eccleston Chrome Chrome Apps Chromebook Chromebox ChromeOS CIA CitiCards Citizen Journalism Civil Liberties Climate Change Clinton Cluster Computing Command Line Tools Comment Systems Computer Accessories Computer Hardware Computer Repair Computers Conservatives Cross Compilation Crouton Cryptocurrency Curiosity Rover Currencies Cyber Security Cybermen Cybersecurity Daleks Darth Vader Data backup Data Formats Data Storage Database Database Backup Databases David Tenant DDoS Botnet Department of Defense Department of Justice Detect Adblocker Developers Editors Digital audio Digital Nomad Digital Photography Direct Attach Storage Diskless Booting Disqus DIY DIY Repair DNP3 Do it yourself Docker Docker MAMP Docker Swarm Doctor Who Doctor Who Paradox Doctor Who Review Drobo Drupal Drupal Themes DuckDuckGo DVD E-Books E-Readers Early Computers eGPU Election Hacks Electric Bicycles Electric Vehicles Electron Eliminating Jobs for Human Emdebian Encabulators Energy Efficiency Enterprise Node EPUB ESP8266 Ethical Curation Eurovision Event Driven Asynchronous Express Face Recognition Facebook Fake Advertising Fake News Fedora VirtualBox Fifth Doctor File transfer without iTunes FireFly Flash Flickr Fraud Freedom of Speech Front-end Development G Suite Gallifrey Gig Economy git Github GitKraken Gitlab GMAIL Google Google Adsense Google Chrome Google Gnome Google+ Government Spying Great Britain Green Transportation Hate Speech Heat Loss Hibernate High Technology Hoax Science Home Automation HTTP Security HTTPS Human ID I2C Protocol Image Analysis Image Conversion Image Processing ImageMagick In-memory Computing Incognito Mode InfluxDB Infrared Thermometers Insulation Internet Internet Advertising Internet Law Internet of Things Internet Policy Internet Privacy iOS iOS Devices iPad iPhone iPhone hacking Iron Man iShowU Audio Capture iTunes Janet Fielding Java JavaFX JavaScript JavaScript Injection JDBC John Simms Journalism Joyent jQuery Kaspersky Labs Kext Kindle Kindle Marketplace Large Hadron Collider Lets Encrypt LibreOffice Linux Linux Hints Linux Single Board Computers Logging Mac Mini Mac OS Mac OS X Mac Pro MacBook Pro Machine Learning Machine Readable ID Macintosh macOS macOS High Sierra macOS Kext MacOS X setup Make Money Online Make Money with Gigs March For Our Lives MariaDB Mars Mass Violence Matt Lucas MEADS Anti-Missile Mercurial MERN Stack Michele Gomez Micro Apartments Microsoft Military AI Military Hardware Minification Minimized CSS Minimized HTML Minimized JavaScript Missy Mobile Applications Mobile Computers MODBUS Mondas Monetary System MongoDB Mongoose Monty Python MQTT Music Player Music Streaming MySQL NanoPi Nardole NASA Net Neutrality Network Attached Storage Node Web Development Node.js Node.js Database Node.js Performance Node.js Testing Node.JS Web Development Node.x North Korea npm NSA NVIDIA NY Times Online advertising Online Community Online Fraud Online Journalism Online News Online Photography Online Video Open Media Vault Open Source Open Source and Patents Open Source Governance Open Source Licenses Open Source Software OpenAPI OpenJDK OpenVPN Palmtop PDA Patrick Troughton PayPal Paywalls Personal Flight Peter Capaldi Peter Davison Phishing Photography PHP Plex Plex Media Server Political Protest Politics Postal Service Power Control President Trump Privacy Private E-mail server Production use Public Violence Raspberry Pi Raspberry Pi 3 Raspberry Pi Zero ReactJS Recaptcha Recycling Refurbished Computers Remote Desktop Removable Storage Renewable Energy Republicans Retro Computing Retro-Technology Reviews RFID Rich Internet Applications Right to Repair River Song Robotics Robots Rocket Ships RSS News Readers rsync Russia Russia Troll Factory Russian Hacking Rust SCADA Scheme Science Fiction SD Cards Search Engine Ranking Search Engines Season 1 Season 10 Season 11 Security Security Cameras Server-side JavaScript Serverless Framework Servers Shell Scripts Silence Simsimi Skype SmugMug Social Media Social Media Networks Social Media Warfare Social Network Management Social Networks Software Development Software Patents Space Flight Space Ship Reuse Space Ships SpaceX Spear Phishing Spring Spring Boot Spy Satellites SQLite3 SSD Drives SSD upgrade SSH SSH Key SSL Stand For Truth Strange Parts Swagger Synchronizing Files Tegan Jovanka Telescopes Terrorism The Cybermen The Daleks The Master Time-Series Database Tom Baker Torchwood Total Information Awareness Trump Trump Administration Trump Campaign Twitter Ubuntu Udemy UDOO US Department of Defense Video editing Virtual Private Networks VirtualBox VLC VNC VOIP Vue.js Walmart Weapons Systems Web Applications Web Developer Resources Web Development Web Development Tools Web Marketing Webpack Website Advertising Website Business Models Weeping Angels WhatsApp William Hartnell Window Insulation Windows Windows Alternatives Wordpress World Wide Web Yahoo YouTube YouTube Adpocalypse YouTube Monetization