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

使用最新版本的 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

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章