【问题标题】:How can I use the regenerator-runtime polyfill conditionally?如何有条件地使用 regenerator-runtime polyfill?
【发布时间】:2017-03-11 19:35:07
【问题描述】:

This article 启发我将我正在为我的 React 应用程序加载的 polyfill 外部化,并且只为需要它们的浏览器加载它们。一个简单的测试:

function browserSupportsAllFeatures() {
  return window.Promise && window.fetch && window.regeneratorRuntime
}

然后将确定是否应该加载 polyfill:

if (browserSupportsAllFeatures()) {
  // Browsers that support all features run `main()` immediately.
  main()
} else {
  // All other browsers loads polyfills and then run `main()`.
  loadScript('/path/to/polyfills.js', main)
}

function main(err) {
  // Initiate all other code paths.
  // If there's an error loading the polyfills, handle that
  // case gracefully and track that the error occurred.
}

但是,我在我的代码中使用了生成器,这似乎有点极端。据我了解,babel 转换生成器(https://babeljs.io/docs/plugins/transform-regenerator/),然后转译的代码也需要定义regeneratorRuntime(使用this package)。

所以我的应用程序失败了,因为在导入 App 时未定义 regeneratorRuntime(其中包含使用生成器的代码)。所以我的 polyfill 为时已晚:

// import dependencies
import React from 'react'
import { render } from 'react-dom'
import { App } from './components/app'

const renderApp = () => {
  render(<App />, document.getElementById('app'))
}

function browserSupportsAllFeatures() {
  return window.Promise && window.fetch && window.regeneratorRuntime
}

if (browserSupportsAllFeatures()) {
  renderApp()
} else {
  loadScript('/path/to/polyfills.js', renderApp);
}

我知道我可以通过在顶部导入 regenerator 来解决这个问题,但这里的目的是外部化 polyfill 并使它们有条件。

所以我的问题是;如何继续使用生成器,但仍将我的 polyfill 包含在 loadScript 调用中?

【问题讨论】:

    标签: javascript reactjs webpack generator babeljs


    【解决方案1】:

    您可以使用以下方法检查属性:

    if (window.hasOwnProperty("regeneratorRuntime")) ...
    

    有一个 npm 包 polyfill-io-feature-detection 完全一样,看看这个解决方案,看看它是如何处理特征检测的: https://github.com/jquintozamora/polyfill-io-feature-detection

    【讨论】:

      【解决方案2】:

      大多数现代浏览器都支持异步函数/生成器。 但 IE 不支持它。

      据我了解,纯粹动态添加 polyfill 是不可能的。因此,您必须为不支持它的浏览器(通常不支持 es6)生成另一个应用程序包。

      有一篇文章很好地解释了如何做到这一点。 https://philipwalton.com/articles/deploying-es2015-code-in-production-today/

      基本上它依赖于&lt;script type="module"&gt;

      【讨论】:

        猜你喜欢
        • 2021-04-24
        • 2015-12-24
        • 1970-01-01
        • 2020-03-14
        • 2023-03-15
        • 2019-06-11
        • 2020-05-06
        • 1970-01-01
        • 2020-01-01
        相关资源
        最近更新 更多