gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:54:21 29 4
gpt4 key购买 nike

我一直在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com