使用 Webpack 延迟加载 AngularJS 个控制器

Lazy load AngularJS controllers with Webpack

我正在使用 AngularJS 1.5.6 和 Webpack。

我的文件架构是:

app
|- scripts
|   |- modules
|       |- homepage
|          |- homepage.js
|          |- controller
|             |- HomepageController.js
|- app.js
|- index.html

webpack.config(如果您需要查看此文件的更多内容,请告诉我):

module.exports = {
    context : __dirname + "/app",
    entry : {
        main: "./app.js",
        vendor: [
            'angular',
            'angular-route'
        ]
    },
[...]
};

index.html包含js文件的导入:

<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="main.js"></script>

apps.js:

(function () {  
    'use strict';

    require('./scripts/modules/homepage/homepage');

    angular.module("NgAppProject", [
        'ngRoute',
        'ng',
        'Homepage'
    ]);
})();

homepage.js中:

(function () {
    'use strict';

    angular.module('Homepage', [
        'ngRoute',
        'ng'
    ])
    .config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider) {
        $routeProvider
          .when('/home', {
            templateUrl: 'scripts/modules/homepage/views/homepage.html',
            controller: 'HomepageController',
            controllerAs: 'homepageController',
            resolve: {
                deps: function() {
                    return require.ensure([], function (require) {
                $controllerProvider.register("HomepageController", require('./controllers/HomepageController'));
                    }, '_homepage');
                }
            }
          });
    }]);
})();

问题:

当我启动我的应用程序并转到 localhost:8080/#/home 时,出现错误:

Error: [ng:areq] Argument 'HomepageController' is not a function, got undefined

我认为它找不到我的控制器,但我不明白为什么。

然而这很好用:

angular.module('Homepage', [
    'ngRoute',
    'ng'
])
.config(//config here)
.controller("HomepageController", require('./controllers/HomepageController'));

非常欢迎任何帮助,谢谢!

我认为 require.ensure 不是 return 承诺。所以,你可以试试这个方法:

resolve: {
  deps: ['$q', function($q) {
    var deferred = $q.defer();
    require.ensure([], function(require) {
      $controllerProvider.register("HomepageController", require('./controllers/HomepageController'));
      deferred.resolve();
    }, '_homepage');
    return deferred.promise;
  }]
}