【发布时间】: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