使用最新版本的 create-react-app(v2.1.0)建立 react 项目时,在 IE 9 & IE 10 中碰到了"Map未定义"的报错:javascript
很明显,这是 IE9 对 ES6 的兼容性问题。首先尝试了两种方式:html
import 'react-app-polyfill/ie9'
import 'core-js/es6/map' import 'core-js/es6/set'
这两种方案的结果是使用 yarn build
打包以后,在 IE9 中运行无问题,可是在开发模式下依然报错。java
此时能够判定,是在开发模式中执行的某些代码具备兼容性问题,而且这些代码是先于 index.js 执行的。node
因而,经过在 index.html 文件的头部引入 es6-sham 和 es6-shim,保证执行全部代码前执行 polyfill 脚本,解决了该兼容性问题。react
... <title>React App</title> <script src="./es6-sham.js"></script> <script src="./es6-shim.js"></script> </head> ...
谈到这里可能有同窗会问,polyfill、es6-sham、es6-shim 分别是什么呢?git
Dr. Axel Rauschmayer 是这么解释的:es6
A shim is a library that brings a new API to an older environment, using only the means of that environment.A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will. Thus, a polyfill is a shim for a browser API. You typically check if a browser supports an API and load a polyfill if it doesn't. That allows you to use the API in either case.github
shim 的意思是“垫片”,polyfill 的意思是“腻子粉”,都有填平间隙的比喻义。惟一的不一样在于,polyfill 是特定与浏览器环境的,而 shim 则能够用于各类环境,如 node etc. es6-shim 则是为原生不支持 ES6 的运行环境提供的脚本。浏览器
那么,sham 又是什么呢?stackoverflow 中的一个回答是这样的:app
The shams, however contain those features that can not be emulated with other code. They basically provide the API, so your code doesn't crash but they don't provide the actual functionality.
sham 的意思是“赝品”,它主要用于模拟一些没法用其余代码实现的 API,防止代码 crash;可是,它们也没法提供该 API 真正的功能,因此,是一种 saliently fail 的手段。一些常见的 sham 能够参见 es5-sham 和 es6-sham。
(完)