简体   繁体   English

使用babel将ES6编译为ES5时,为什么浏览器需要polyfills文件

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

如果babel将ES6转换为ES5并输出ES5文件,那么如果应用程序输出文件中恰好包含ES5代码,为什么浏览器需要包含polyfill文件?

Babel translates ES6 (and newer) code into ES5 code. Babel将ES6(及更新版本)代码转换为ES5代码。 For example, it rewrites arrow functions ( () => {} ) to ES5 functions ( function() {} ). 例如,它将箭头函数( () => {} )重写为ES5函数( function() {} )。 However, ES6 is much more than just some new syntax. 但是,ES6不仅仅是一些新语法。

https://babeljs.io : 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). 由于Babel仅转换语法(如箭头函数),因此可以使用babel-polyfill来支持Promise之类的新全局变量或String.padStart之类的新本机方法(左键盘)。 It uses core-js and regenerator. 它使用core-js和regenerator。 Check out our babel-polyfill docs for more info. 查看我们的babel-polyfill文档以获取更多信息。

All the new functions need to be implemented with a polyfill. 所有新功能都需要使用polyfill来实现。 And these polyfills must be included globally to your project. 并且这些polyfill必须全局包含到您的项目中。 Otherwise every usage of an ES6 function would be replaced by the implementation of that function in ES5 code. 否则,ES6功能的每次使用都将被ES5代码中该功能的实现所取代。 So if you use eg Array#findIndex ten times, the transpiled code would also contain the implementation ten times. 因此,如果您使用例如Array#findIndex十次,则转码后的代码还将包含十次实现。 That is why the polyfills have to be added globally and are not just added by the transpilation step. 这就是为什么必须全局添加polyfill的原因,而不仅仅是通过转嫁步骤添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM