Babel 不能自动解决全部的 polyfill,手动添加一些 polyfill

Babel 不能自动解决全部的 polyfill,手动添加一些 polyfill

为什么 babel 不能彻底解决全部的 polyfill ?
因为 babel 是扫描全部的静态代码,分析出开发者使用的 ES6 ES7 等特性,
但是当你使用了一些对象的原型上东西, babel 不能确定你用的是什么。
JavaScript 是一门动态类型的语言,js 内置对象的原型也都是篡改的,所以 babel 不能分析出你用了哪些原型上的 ES6-7 特性。


示例:
开发中的代码,直接调用这样的函数:
Date.now()
Array.from() 
Promise.resolve()
这样,babel 是能分析出你使用的新特性。

但是:
const a1 = [1, 2, 3]
a1.includes(1)
这时候,babel 是不能确定这个 includes 是什么。
因为你可能自己在 a1 手动添加了一个函数,或者你篡改了 Array.prototype 上的 includes() ,
babel 并从静态代码上分析出你用了什么新特性。
加入 babel 从运行时进行分析,相对比静态分析要准确一些。

所以,我们开发中最好手动添加自己所要的 polyfill。
添加 polyfill 示例:
import 'core-js/modules/es7.array.includes'
import 'core-js/modules/es6.string.includes'
import 'core-js/modules/es6.array.find'
import 'core-js/es6/promise'


像上面这样,就可以更方便的使用 ES6、ES7 了。
但注意:
polyfill 引入的位置,应该是在全部代码的最前面,最开始就加载 polyfill,避免后面代码执行的时候报错。


小提示:
你可能用得上这个,IE9 等IE系列的浏览器 有个小问题:location.origin 取值,得到的是:undefined,
我们也可以在 polyfill 中解决这个问题:
// fix IE location.origin undefined
// https://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url#answer-19285047
const location = window.location
if (!location.origin) {
  location.origin = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '')
}
这样之后,在 IE 上使用 location.origin 也就安全了,获取的值不再是 undefined 。