javascript - 在使用 create-react-app 的 React 应用程序中填充 ES6 功能的最佳方法

标签 javascript reactjs ecmascript-6 create-react-app ecmascript-2016

我一直在 Internet Explorer 上测试我的 React.js 应用程序,发现一些 ES6/7 代码(例如 Array.prototype.includes())会破坏它。

我正在使用create-react-app ,显然他们选择不包含大量的polyfill,因为不是每个人都需要它们,并且它们会减慢构建时间(例如参见 herehere )。文档(在撰写本文时)建议:

If you use any other ES6+ features that need runtime support (such as Array.from() or Symbol), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.

那么...“手动”包含它们的最佳方法是什么?

最佳答案

更新:自此问题/答案以来,create-react-app polyfill 方法和文档已发生更改。如果您想支持 ie11 等旧版浏览器,您现在应该包含 react-app-polyfill ( here )。但是,这仅包括“...最低要求和常用语言功能”,因此您仍然需要使用以下方法之一来实现不太常见的 ES6/7 功能(例如 Array.includes)

<小时/>

这两种方法都有效:

<小时/>

<强>1。从react-app-polyfill和core-js手动导入

安装react-app-polyfillcore-js (3.0+):

npm install react-app-polyfill core-jsyarn add react-app-polyfill core-js

创建一个名为(类似)polyfills.js 的文件并将其导入到根index.js 文件中。然后导入基本的react-app polyfill,以及任何特定的所需功能,如下所示:

/* 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 服务

使用polyfill.io CDN 通过将此行添加到 index.html 来检索自定义的、特定于浏览器的 polyfill:

<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default,Array.prototype.includes"></script>

注意,我必须明确请求 Array.prototype.includes 功能,因为它不包含在默认功能集中。

关于javascript - 在使用 create-react-app 的 React 应用程序中填充 ES6 功能的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43756211/

相关文章:

javascript - 如何获取 JavaScript 字符串中的字符数

php - 我在 Chrome 中看不到带有 onmessage 方法的 HTML5 EventSource 事件

javascript - 提交后如何在handleSubmit方法中重新加载页面/路由器?

reactjs - 如何使用 Visual Studio Code 的发布配置文件在 azure 上部署 React 应用程序

javascript - 嵌套的 json 需要借助 Angular 以树结构格式动态显示

javascript - 为什么我的 json 数据没有被使用 jquery 从 every 循环中获取?

javascript - 谷歌地图上的明确指示

javascript - ReactJS react-grid-layout 切换静态属性

javascript - ES6 类默认值

javascript - 范围不是 lodash 中的函数?