getChildRoutes动态

时间:2016-06-07 08:08:22

标签: reactjs react-router

在react-router示例中,为动态加载子项提供以下代码,但我想动态计算依赖项。但是,它似乎不起作用。 forEach

表示"Cannot find module xxx"循环会抛出错误
getChildRoutes(location, callback) {
    require.ensure([], function (require) {
      callback(null, [
        require('./routes/Announcements'),
        require('./routes/Assignments')
      ])
    })
  },

---- ########################################### #### ----

getChildRoutes(location, callback) {
  require.ensure([], function (require) {
  var appsRoutes = ['routes/Announcements', 'routes/Assignments'].forEach(item=>{
    return require('./' + item);
  });
          callback(null, appRoutes)
  })
},

1 个答案:

答案 0 :(得分:0)

以下变体是否有效?

const dynamicRoutes = [
 './routes/Announcements', 
 './routes/Assignments'
];

...

getChildRoutes(location, callback) {
  require.ensure(dynamicRoutes, function (require) {
    var appsRoutes = dynamicRoutes.map(item => require(item));
    callback(null, appRoutes); 
  });
},

我认为webpack需要能够计算在编译期间创建动态挂钩的模块,由于你的concat forEach循环方法,它无法解决。

这种替代方案也可能有效:

 getChildRoutes(location, callback) {
   require.ensure([], function (require) {
     var appsRoutes = [
       require('./routes/Announcements'),
       require('./routes/Assignments')
     ];
     callback(null, appRoutes);
   });
 },

请点击此处了解详情:https://webpack.github.io/docs/code-splitting.html