【问题标题】:React Router Webpack async chunk loadingReact Router Webpack 异步块加载
【发布时间】:2016-02-11 04:12:29
【问题描述】:

我有一个路由组件,我想用 webpack 异步加载它:

<Route path="dashboard" getComponent={(location, cb) => {
  require.ensure([], (require) => {
    cb(null, require('./Containers/Dashboard'));
  });
}}>

如果您有很多其他需要异步块加载的路由,那么这是很多样板文件。所以我想,让我们把它重构为一个辅助方法:

const loadContainerAsync = route => (location, cb) => {
  require.ensure([], (require) => {
    cb(null, require('../Containers/' + route));
 });
};

// much 'nicer syntax'
<Route path="dashboard" getComponent={loadContainerAsync('Dashboard')} />

显然,当我查看 firefox-devtools 中的网络选项卡时,loadContainerAsync 函数的行为无法正常运行。知道我的函数 loadContainerAsync 有什么问题吗?

【问题讨论】:

    标签: webpack react-router


    【解决方案1】:

    我想你可以试试bundle-loader

    const loadContainerAsync = bundle => (location, cb) => {
      bundle(component => {
        cb(null, component);
      });
    };
    
    // 'not so nice syntax', but better than first option :)
    <Route path="dashboard" getComponent={loadContainerAsync(require('bundle?lazy!../containers/Dashboard'))} />
    

    别忘了$ npm install bundle-loader --save-dev

    【讨论】:

    • 谢谢,这暂时解决了问题。语法没有 require.ensure 回调地狱那么糟糕;)
    • 这不适用于同构应用程序。 require('bundle?lazy!') 爆炸了... :(
    • 关于为什么 webpack 甚至不会根据 require.ensure 语句生成块的任何想法。
    • 看看这里:webpack.github.io/docs/context.html#context-module。 Webpack 将在 require.ensure 上生成块,但如果它是动态 require,则所有可以匹配该 require 的文件都将在同一个块中结束
    【解决方案2】:

    getComponent 需要一个函数,你可以试试:

    const loadContainerAsync = route => (location, cb) => {
      return (location, cb) => {
        require.ensure([], (require) => {
          cb(null, require('../Containers/' + route));
        });
      }
    };
    

    【讨论】:

    • 对不起,我忽略了你已经将它包装在一个方法中的事实(该死的 ES6 :)
    • Np :) 一定喜欢 ES6 ;p
    猜你喜欢
    • 2016-11-03
    • 1970-01-01
    • 2018-06-26
    • 2015-11-28
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多