Javascript Intl.js polyfill/shim与网页包?

Javascript Intl.js polyfill/shim与网页包?,javascript,reactjs,webpack,polyfills,Javascript,Reactjs,Webpack,Polyfills,我使用with,我需要垫片来支持Safari和IE,但我不想为已经支持的浏览器加载它 polyfill相当大(900kb),如何确保它只在不支持它的浏览器中加载?您需要做一些事情 确保需要加载核心库而不是所有相关国家/地区的intl/intl。这将使库的大小从约900kb减少到约150kb 使用网页包的require。确保或require([])函数仅在需要时动态地需要Intl.js。这将为Intl.js文件创建一个单独的包,该文件将根据需要加载 lib/shim.js // shim for

我使用with,我需要垫片来支持Safari和IE,但我不想为已经支持的浏览器加载它


polyfill相当大(900kb),如何确保它只在不支持它的浏览器中加载?

您需要做一些事情

  • 确保需要加载核心库而不是所有相关国家/地区的
    intl/intl
    。这将使库的大小从约900kb减少到约150kb

  • 使用网页包的
    require。确保
    require([])
    函数仅在需要时动态地需要Intl.js。这将为Intl.js文件创建一个单独的包,该文件将根据需要加载

  • lib/shim.js

    // shim for Intl needs to be loaded dynamically
    // so we callback when we're done to represent
    // some kind of "shimReady" event
    module.exports = function(callback) {
        if (!window.Intl) {
            require(['intl/Intl'], function(Intl) {
                window.Intl = Intl;
                callback();
            });
        } else {
            setTimeout(callback, 0); // force async
        }
    };
    
    var shimReady = require('lib/shim');
    shimReady(startApp);
    
    app.js

    // shim for Intl needs to be loaded dynamically
    // so we callback when we're done to represent
    // some kind of "shimReady" event
    module.exports = function(callback) {
        if (!window.Intl) {
            require(['intl/Intl'], function(Intl) {
                window.Intl = Intl;
                callback();
            });
        } else {
            setTimeout(callback, 0); // force async
        }
    };
    
    var shimReady = require('lib/shim');
    shimReady(startApp);
    
    注意:您可能还需要访问特定国家/地区的信息和财产。对于我的基本需求,我实际上并不需要这些数据,但如果您确实需要,请务必阅读Intl.js网站上的部分。

    一种简单的(非网页包)方法是在HTML中执行以下操作:

    <script>
     if (!window.Intl) { document.write('<script src="/js/Intl.min.js"><\/script>'); }
    </script>
    
    
    如果(!window.Intl){document.write(“”);}
    
    虽然
    document.write
    不被视为最佳实践,但这将提供一种解决问题的阻塞方法,从而大大减少应用程序中的代码。此解决方案不使用webpack,但对于许多处于这种情况的人来说可能是一个合适的解决方案