Polyfills and Transpilers
JavaScript constantly evolves, adding new syntax and methods yearly via the ECMAScript standard.
If you are writing backend JavaScript (Node.js), utilizing new features is easy: you simply update your server’s Node version. However, if you are writing frontend JavaScript, you do not control the runtime. You are at the mercy of whatever web browser your user happens to have installed. If a user is running an outdated browser, your modern JavaScript might completely crash their page.
To solve this, the industry relies on Polyfills and Transpilers.
Polyfills
A polyfill is a snippet of JavaScript code that provides modern functionality to older browsers that natively lack it.
For example, if you want to use the modern Array.prototype.flat() method, you can include a polyfill script. If the browser is modern, the polyfill does nothing. If the browser is old (like Internet Explorer), the polyfill manually attaches a custom flat() method to the Array prototype so your code doesn’t crash.
Transpilers
A transpiler is essentially a heavy-duty compiler for JavaScript syntax.
Instead of just injecting missing methods, a transpiler reads your entire source code file and completely rewrites modern syntax (like async/await or Template Literals) into older, uglier JavaScript (like Promises and standard string concatenation) that is guaranteed to work on all browsers.
Babel is the most famous JavaScript transpiler.
Using Babel
In a modern Node project, you might use Babel via NPM to transpile a file:
- Install the Babel toolchain:
npm i -D @babel/core @babel/cli @babel/preset-env - Configure
.babelrcto usepreset-env(which automatically determines what needs transpiling based on target browsers). - Run the transpiler:
npx babel main.js --out-file main.compiled.js
The resulting main.compiled.js file can be safely shipped to the web, knowing it will execute perfectly even on older hardware.