What is the difference between polyfill and transpiler?

后端 未结 5 887
离开以前
离开以前 2021-02-01 02:37

What is the difference between a polyfill and transpiler?

I often read the same term used in similar context.

5条回答
  •  走了就别回头了
    2021-02-01 03:05

    Both pollyfill and transpilation enable you to use new features in old environments (old vs new browsers for example), the main difference is that a pollyfill do that by implementing the feature in the old environment itself. So if we go by Es6 Es5 terminology, polyfill enable you to use a new feature by implementing it in Es5, however some new features can never be implemented in Es5, think for example about the arrow syntax introduced by Es6 and this is where transpilation is needed.

    So an example where transpilation is needed is arrow syntax (() => {}) because u can never implement that in es5, and an example where a pollyfil can be used is for example if u wanted to implement the Array.prototype.includes method, you can easily implement it like this

    // taken from mdn
    if (!String.prototype.includes) {
      String.prototype.includes = function(search, start) {
        'use strict';
    
        if (search instanceof RegExp) {
          throw TypeError('first argument must not be a RegExp');
        } 
        if (start === undefined) { start = 0; }
        return this.indexOf(search, start) !== -1;
      };
    }
    

    Now here are some major differences:

    • A pollyfill will use the native feature if it exists, however transpilation will not. that leads to the conclusion that Polyfills should be preferred over transpilation, because of security and performance reasons.
    • Transpilation is about language syntax, while pollyfill is about language syntax and native browser APIs (or other environment APIs).
    • Transpilation is at compile time, while pollyfill is at runtime, and this is what differentiates one from the other.

提交回复
热议问题