使用 oclazyload 和 webpack 代码拆分避免 angular 路由中的代码重复

Avoid code duplication in angular routing with oclazyload and webpack code splitting

我目前在项目中使用 angular 1.5,我的路由如下所示:

const routes = ($stateProvider) => {

  $stateProvider
    .state('update', {
      url: '/update',
      template: '<update></update>',
      resolve: {
        lazyload: [ '$q', '$ocLazyLoad', function ($q, $ocLazyLoad) {
             console.log('start lazy');
             let deferred = $q.defer();
             require.ensure([], function () {
             let module = require('../components/update/update.module');
               let module = require('../components/update/update.module');
               $ocLazyLoad.load({
                 name: module.default.name
               });
               deferred.resolve(module);
             });
             return deferred.promise;
           }
         ]
      }
    })
    .state('login', {
      url: '/login',
      template: '<login></login>',
      resolve: {
        lazyload: [ '$q', '$ocLazyLoad', function ($q, $ocLazyLoad) {
            let deferred = $q.defer();
            require.ensure([], function () {
              let module = require('../components/login/login.module');
              $ocLazyLoad.load({
                name: module.default.name
              });
              deferred.resolve(module)
            });
            return deferred.promise;
          }
        ]
      }
    });

};

当我尝试在一个单独的函数中提取重复代码时:

function load (modulePath) {
    return function ($q, $ocLazyLoad) {
      let deferred = $q.defer();
      require.ensure([], function () {
      let module = require(modulePath);
        $ocLazyLoad.load({
          name: module.default.name
        });
        deferred.resolve(module);
      });
      return deferred.promise;
    }
  }

并以这种方式使用加载函数:

$stateProvider
    .state('update', {
      url: '/update',
      template: '<update></update>',
      resolve: {
        lazyload: [ '$q', '$ocLazyLoad', load('../components/update/update.module')]
      }
    })

路由不再工作,我收到此错误 "Cannot find module "。”在 webpackMissingModule“

使用动态要求时,不要在参数中包含路径和扩展名。

将所有你需要的惰性模块放在一个单独的文件夹中 lazy

function load (state) {
  return function ($q, $ocLazyLoad) {
    let deferred = $q.defer();
    require.ensure([], function () {
      let module = require('../components/lazy/' +state+ '.module');
      $ocLazyLoad.load({
        name: module.default.name
      });
      deferred.resolve(module);
    });
    return deferred.promise;
  }
}

$stateProvider
.state('update', {
  url: '/update',
  template: '<update></update>',
  resolve: {
    lazyload: [ '$q', '$ocLazyLoad', load('update')]
  }
})

您可以使用与建议结构不同的结构。参考 https://webpack.github.io/docs/context.html#dynamic-requires