Today I Learned - Rocky Kev

TIL transpiling VS polyfills

POSTED ON:

TAGS:

Transpiling is a contrived and community-invented term to describe using a tool to convert the source code of a program from one form to another (but still as textual source code). Typically, forwards-compatibility problems related to syntax are solved by using a transpiler (the most common one being Babel (https://babeljs.io)) to convert from that newer JS syntax version to an equivalent older versions.

Transpiling

Example:
(Note: As of 2020, this will work without transpiling but it's just an example)

if (something) {
    let x = 3;
    console.log(x);
    }
else {
    let x = 4;
    console.log(x);
}

This is how the code would look in the source code tree for that application. But when producing the file(s) to deploy to the public website, the Babel transpiler might convert that code to look like this:

var x$0, x$1;
if (something) {
    x$0 = 3;
    console.log(x$0);
}
else {
    x$1 = 4;
    console.log(x$1);
}

Polyfills

This pattern is called a polyfill (aka “shim”).

// getSomeRecords() returns us a promise for some
// data it will fetch

var pr = getSomeRecords(); // show the UI spinner while we get the data

startSpinner();

pr
    .then(renderRecords)   // render if successful
    .catch(showError)      // show an error if not
    .finally(hideSpinner)  // always hide the spinner

This code uses an ES2019 feature, the finally(..) method on the promise prototype. If this code were used in a pre-ES2019 environment, the finally(..) method would not exist, and an error would occur.

A polyfill for finally(..) in pre-ES2019 environments could look like this:

if (!Promise.prototype.finally) {
Promise.prototype.finally = function f(fn){
        return this.then(
            function t(v){
                return Promise.resolve( fn() )
                    .then(function t(){
                        return v;
                    });
            },
            function c(e){
                return Promise.resolve( fn() )
                    .then(function t(){
                        throw e;
                    });
            }
        );
    };
}

Via You Don't Know JS (2nd edition)


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.