2017-03-11 14 views
0

This articleは私のReactアプリケーションのために読み込んでいるポリフィルを外部化し、それらを必要とするブラウザのためだけにロードしました。簡単なテスト:リジェネレータランタイムポリフィルを条件付きで使用するにはどうすればよいですか?

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. 
} 

しかし、私は私のコードで発電機を使用しているんだエッジ例ビットのようだ:polyfillsをロードする必要がある場合

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

はその後、決定します。私が知っていることから、バーベルはジェネレーター(https://babeljs.io/docs/plugins/transform-regenerator/)を変換し、変換されたコードもregeneratorRuntimethis package)と定義する必要があります。

したがって、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をexternaliseし、それらを条件付きにすることです。

私の質問です。どのように私はジェネレータを使用し続けることができますが、私のpolyfillsはloadScriptコールに含まれていますか?

答えて

0

あなたが使用してプロパティを確認することができます。

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

正確に同じことをNPMパッケージポリフィル-IO-機能-検出があり、それは特徴検出を処理する方法を表示するには、このソリューションに見てみましょう: https://github.com/jquintozamora/polyfill-io-feature-detection

関連する問題