Why does a browser need a polyfills file while I compile ES6 to ES5 with babel

If babel translates ES6 to ES5 and outputs an ES5 file then why does a browser need to include a polyfill file if an app output file contains exactly ES5 code ?

Upvotes: 0

Views: 398

Answers (1)

str
str

Reputation: 44969

Babel translates ES6 (and newer) code into ES5 code. For example, it rewrites arrow functions (() => {}) to ES5 functions (function() {}). However, ES6 is much more than just some new syntax.

https://babeljs.io:

Since Babel only transforms syntax (like arrow functions), you can use babel-polyfill in order to support new globals such as Promise or new native methods like String.padStart (left-pad). It uses core-js and regenerator. Check out our babel-polyfill docs for more info.

All the new functions need to be implemented with a polyfill. And these polyfills must be included globally to your project. Otherwise every usage of an ES6 function would be replaced by the implementation of that function in ES5 code. So if you use e.g. Array#findIndex ten times, the transpiled code would also contain the implementation ten times. That is why the polyfills have to be added globally and are not just added by the transpilation step.

Upvotes: 1

Related Questions