![](/img/trans.png)
[英]Babel and Webpack are throwing "Can't resolve 'regenerator-runtime/runtime'"
[英]How can I use the regenerator-runtime polyfill conditionally?
這篇文章激勵我將我正在為我的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
(使用此包 )。
因此我的應用程序失敗,因為導入App
時未定義regeneratorRuntime
(其中包含使用生成器的代碼)。 所以我的polyfills太晚了:
// 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);
}
我知道我可以通過在頂部導入再生器來解決這個問題,但這里的目的是將polyfills外部化並使它們成為條件。
所以我的問題是; 如何繼續使用生成器,但仍然將我的polyfill包含在loadScript
調用中?
您可以使用以下方式查看酒店:
if (window.hasOwnProperty("regeneratorRuntime")) ...
npm包polyfill-io-feature-detection完全相同,看看這個解決方案,看看它如何處理功能檢測: https : //github.com/jquintozamora/polyfill-io-feature-detection
大多數現代瀏覽器都支持異步函數/生成器。 但它在IE中不受支持。
據我所知,不可能純粹動態地添加polyfill。 因此,您必須為不支持它的瀏覽器生成另一個應用程序包(通常不支持es6)。
有一篇文章很好地解釋了如何做到這一點。 https://philipwalton.com/articles/deploying-es2015-code-in-production-today/
基本上它依賴於<script type="module">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.