【问题标题】:How to add polyfill for String.repeat function for ie11?如何为 ie11 的 String.repeat 函数添加 polyfill?
【发布时间】:2020-02-28 13:45:17
【问题描述】:

如何为 ie11 的 String.repeat 方法添加 polyfill?我没有直接在我的代码中使用它,它可能是一些导入的库。

在 IE 控制台中出现此错误:Object doesn't support property or method 'repeat'

我也得到了'AbortController' is undefined,我也没有使用我的代码,可能又是外部库。

我正在使用 create react app 并在 index.js 中导入:

import 'react-app-polyfill/ie9';
import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';

我尝试将 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#Polyfill 添加到我的 index.js 中,但它没有做任何事情。

其他人有类似的问题吗?

【问题讨论】:

  • 为 IE 使用 polyfill 对我有用。
  • 你是否在 index.js 的第一行导入了 polyfill?您是否按照this answer 中的步骤支持 IE 11 中的 React 应用程序?此外,您可以将this polyfill 用于AbortController。如果还是不行,请提供a minimal, reproducible code sample,以便我们进行测试,看看如何提供帮助。

标签: javascript reactjs internet-explorer-11 create-react-app polyfills


【解决方案1】:

要为 IE11 添加 String.repeat polyfill,我建议使用 core-js 库来填充缺失的功能。

通过运行以下命令安装core-js

npm install --save core-js@3.6.5

src/index.js 内部,在最顶部导入适当的polyfill:

import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
import 'core-js/features/string/repeat';

import React from 'react';
// ...

至于AbortController,运行如下命令安装:

npm install --save abortcontroller-polyfill

编辑您的 src/index.js 文件以将其导入:

import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
import 'core-js/features/string/repeat';
import 'abortcontroller-polyfill';

import React from 'react';
// ...

【讨论】:

    【解决方案2】:

    这是针对 IE 的 ES6 不兼容问题。

    使用 npm 添加以下 polyfills

    promise-polyfill
    unfetch
    abortcontroller-polyfill
    

    然后像这样导入它们

    import Promise from "promise-polyfill";
    import fetch from 'unfetch';
    import 'abortcontroller-polyfill';
    

    Abortcontroller

    &对于Object.repeat 将 MDN 的 polyfill 代码复制并粘贴到您的第一个 JS 文件中。 这样就可以了。

    编辑 对于 React,这应该看起来像这样 (你可以在 index.js 中做到这一点)

    // import polyfills
    import 'react-app-polyfill/stable';
    import 'react-app-polyfill/ie11';
    
    import Promise from "promise-polyfill";
    import fetch from 'unfetch';
    import 'abortcontroller-polyfill';
    

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 1970-01-01
      • 2020-03-23
      • 2017-07-17
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      相关资源
      最近更新 更多