解决 create-react-app IE 兼容性问题

4,532 阅读2分钟

使用最新版本的 create-react-app(v2.1.0)创建 react 项目时,在 IE 9 & IE 10 中碰到了"Map未定义"的报错:

很明显,这是 IE9 对 ES6 的兼容性问题。首先尝试了两种方式:

  1. 使用 create-react-app 官方提供的 react-app-polyfill,然后在入口文件 index.js 中引入:
import 'react-app-polyfill/ie9'
  1. 根据 react 官方文档,使用 core-js 引入 polyfill:
import 'core-js/es6/map'
import 'core-js/es6/set'

这两种方案的结果是使用 yarn build 打包之后,在 IE9 中运行无问题,但是在开发模式下依然报错。

此时可以断定,是在开发模式中执行的某些代码具有兼容性问题,并且这些代码是先于 index.js 执行的。

于是,通过在 index.html 文件的头部引入 es6-sham 和 es6-shim,保证执行所有代码前执行 polyfill 脚本,解决了该兼容性问题。

...
        <title>React App</title>
        <script src="./es6-sham.js"></script>
        <script src="./es6-shim.js"></script>
    </head>
...

谈到这里可能有同学会问,polyfill、es6-sham、es6-shim 分别是什么呢?

Dr. Axel Rauschmayer 是这么解释的:

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.

shim 的意思是“垫片”,polyfill 的意思是“腻子粉”,都有填平间隙的比喻义。唯一的不同在于,polyfill 是特定与浏览器环境的,而 shim 则可以用于各种环境,如 node etc. es6-shim 则是为原生不支持 ES6 的运行环境提供的脚本。

那么,sham 又是什么呢?stackoverflow 中的一个回答是这样的:

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-shames6-sham

(完)