我一直在Internet Explorer上测试我的React.js应用程序,发现有些ES6 / 7代码Array.prototype.includes()会破坏它。
Array.prototype.includes()
我正在使用create-react-app,并且显然它们选择不包含很多polyfill,因为不是每个人都需要它们,并且它们会减慢构建时间(请参见此处和此处的示例)。该文档(在撰写本文时)建议:
如果您使用任何其他需要运行时支持的ES6 +功能(例如Array.from()或Symbol),请确保手动添加了适当的polyfill,或者要使用的浏览器已经支持它们。
那么… “手动”包含它们的最佳方法是什么?
更新 :自此问题/答案以来,create-react-app polyfill方法和文档已更改。现在,如果您想支持像ie11这样的旧版浏览器,则应包含react-app- polyfill(here)。但是,这仅包括“ …最低要求和常用语言功能 ”,因此您仍然希望使用以下其中一种方法来处理不太常见的ES6 / 7功能(例如Array.includes)
react-app- polyfill
Array.includes
这两种方法都起作用:
1.从react-app-polyfill和core-js手动导入
安装react-app-polyfill和core- js(3.0+):
npm install react-app-polyfill core-js 要么 yarn add react-app-polyfill core- js
npm install react-app-polyfill core-js
yarn add react-app-polyfill core- js
创建一个名为(类似)polyfills.js的文件,并将其导入您的根index.js文件。然后导入基本的react-app polyfills以及任何特定的必需功能,如下所示:
/* polyfills.js */ import 'react-app-polyfill/ie11'; import 'core-js/features/array/find'; import 'core-js/features/array/includes'; import 'core-js/features/number/is-nan'; /* index.js */ import './polyfills' ...
2. Polyfill服务
通过将以下行添加到index.html,使用polyfill.io CDN来检索自定义的,特定于浏览器的polyfill:
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default,Array.prototype.includes"></script>
请注意,由于该Array.prototype.includes功能未包含在默认功能集中,因此我必须明确要求该功能。
Array.prototype.includes