Search code examples
javascriptwebpackecmascript-6babeljses6-module-loader

How does webpack uses polyfill?


I'm using webpack with babel polyphill so I can write my code in es6.

I don't understand how does webpack use polyfill so my code can be supported in browsers like IE?

For example, let say we have a simple class

class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  } 
}

Since IE doesn't understand what the class keyword is, my code need to be change to:

function Polygon(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  } 

Is that changes occur on run time (using something like a reference to the code that should be interpreted) or is webpack compiling my code so that resulted code is only the es5?

I mean, if that occur on run time, I will have more code in my bundle: the code I wrote + polyphill...

Indeed, when using webpack, my code is (a lot) bigger.

If it doesn't occur on run time so why do I have to include polyphill to my dependencies (instead of in my dev dependencies)?

Thx


Solution

  • is webpack compiling my code so that resulted code is only the es5?

    Yes. Webpack includes babel-polyfill code to your result bundle.

    So if you use native Promise, babel-polyfill will set own implementation to global namespace(window.Promise). There is also babel-runtime package which does not touch global namespace and resolves your Promise in code as local module during webpack bundling.

    If it doesn't occur on run time so why do I have to include polyphill to my dependencies (instead of in my dev dependencies)?

    Because babel-polyfill is required module for your application to work correctly on run-time. dependencies are required to run app, devDependencies only for development, transpilation, testing, etc. So example babel - transpiler (devDependency), babel-polyfill provides missing functionality(api not syntax) to app (dependency).