如何有条件地使用再生器 - 运行时polyfill?

时间:2017-03-11 19:35:08

标签: javascript reactjs webpack generator babel

This article激励我将我为我的React应用加载的polyfill外部化,并仅为需要它们的浏览器加载它们。一个简单的测试:

\"

然后确定是否应加载polyfill:

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

但是,我在我的代码中使用生成器,这似乎是一个边缘情况。根据我的理解,babel转换生成器(https://babeljs.io/docs/plugins/transform-regenerator/),然后转换后的代码也需要定义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. } (使用this package)。

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

App

我知道我可以通过在顶部导入再生器来解决这个问题,但这里的目的是将polyfills外部化并使它们成为条件。

所以我的问题是;我如何继续使用生成器,但仍然将我的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); } 调用中?

2 个答案:

答案 0 :(得分:0)

您可以使用以下方式查看酒店:

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

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

答案 1 :(得分:0)

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

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

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

基本上,它依赖于<script type="module">