Skip to content

Babel: transpilation and polyfills

Benjamin RICHARD edited this page Apr 9, 2018 · 2 revisions

Recently, i had to make an app compatible with IE9 (oh my god). This app alredy exist, and was rather crappy with old JS embedded in HTML... The problem is that most of new features was around 20% of PHP and 80% of javascript. So i considered that it was impossible to continue that way. I decided to allow developpers to write ES6 code, and when they would be ready, i wanted to build new features with VueJS. But when you have to be compatible with IE9 you know that you won't be able to use the new JS code out of the box. Hey, Babel ! would you help us please ?

I already knew Babel as a full JS transpiler. The aim is to write ES6+ and transpile it to ES5. So it was quite easy to embed it in our application and add a new task in our delivery process. But what i forgot is that Babel only do transpilation to ES5. If the aimed browser doesn't feat ES5 features it will not help you... The classic case is the Array.forEach feature. IE9 doesn't implement it. So what ?

This is where comes polyfills ! I was sure that Babel would use polyfill for me if i aimed IE9 browser. But in fact it doesn't. But it embeds a great library that has all known polyfills of the world: CoreJS. CoreJS is a library on which Babel is based and that provides all shim and polyfills for any feature of ecmascript standard. So we created a new file polyfill.js that would embed required feature like this:

// Don't use dynamic import to get Promise available immediatly
require ('core-js/modules/es6.promise')

// dynamic import from babel
require ('babel-polyfill')

// dynamic import for all required shim and polyfills from core-js
require ('core-js/modules/es6.array.for-each.js')

This file is now required in our main app entry to get main missing features. And now we can do what we want, it will be compatible with IE9.

This article helped me a lot: https://hackernoon.com/polyfills-everything-you-ever-wanted-to-know-or-maybe-a-bit-less-7c8de164e423

Clone this wiki locally