解決 create-react-app IE 兼容性問題

使用最新版本的 create-react-app(v2.1.0)建立 react 項目時,在 IE 9 & IE 10 中碰到了"Map未定義"的報錯:javascript

很明顯,這是 IE9 對 ES6 的兼容性問題。首先嚐試了兩種方式:html

  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 中運行無問題,可是在開發模式下依然報錯。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-shames6-sham

(完)

相關文章
相關標籤/搜索