TIL transpiling VS polyfills
POSTED ON:
TAGS: javascript you-dont-know-js
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: javascript