DEV Community

Hash
Hash

Posted on • Updated on

Transpiler and Polyfill

Transpiler

It is a type of compiler that takes code written in one programming language and converts it to another language that has a similar level of abstraction. An example of this is TypeScript, which transpiles TypeScript code to JavaScript.

Babel is a transpiler, check the online repl Babel repl

Babel transforms our code into understandable code for browsers, especially the old versions

for example, it transforms this code

let total = 10;
let sum = total ?? 100;
Enter fullscreen mode Exit fullscreen mode

to

"use strict";

let total = 10;
let sum = total !== null && total !== void 0 ? total : 100;
Enter fullscreen mode Exit fullscreen mode

So it means it transforms the new feature ?? Nullish operator to an understandable code for the browsers that don't know what is Nullish operator.

That is known as a transpiler

caveat: not every modern javascript feature can be transpiled. but these cases developers use another tool name polyfill, like promises and fetch

Polyfill

polyfill in general means we are going to write code which should work in the older browsers
for instance, look this example we want to use function Number.isNaN in our code, and we write this piece of code before use it.

// These method is a sample of making polyfill
if (!Number.isNaN) {
  Number.isNaN = function isNaN(x) {
    return x!==x;
  };
}
Enter fullscreen mode Exit fullscreen mode

If you check Number.isNaN in the website CanIUse, you will see the IE browser doesn't support it, but it works in new browsers. So with that piece of code we first check if it works on the browser or not, if it's not available, then we are writing an equivalent piece of code, so the code will not break on older browsers.
You know there are lots of features and function like this if we want to write a polyfill for them.
Shall we write for all of them? Obviously, it's not possible.

So there are some famous libraries to manage it.
for instance, core-js is a polyfill library that supports almost all new features for all older browsers

you just need to install and import it, then write the code without worrying about the browser support

import 'core-js/actual/array/from';       // <- at the top of 
import 'core-js/actual/set'; 

Array.from(new Set([1, 2, 3, 2, 1]));  

Enter fullscreen mode Exit fullscreen mode

Let's have your reasons as well

Top comments (0)