AngularJS and Webpack Integration

会有一股神秘感。 提交于 2019-12-03 06:37:56

Sagar Ganatra wrote a helpful blog post about code splitting.

Suprisingly code splitting isn't really supported by angular's module system. However, there is a way to achieve code splitting by saving a reference to angular's special providers during the config-phase.

[...] when Angular initializes or bootstraps the application, functions - controller, service etc,. are available on the module instance. Here, we are lazy loading the components and the functions are not available at a later point; therefore we must use the various provider functions and register these components. The providers are available only in the config method and hence we will have to store a reference of these providers in the config function when the application is initialized.

window.app.config([
    '$routeProvider',
    '$controllerProvider',
    '$compileProvider',
    '$filterProvider',
    '$provide',
    function ($routeProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {

        $routeProvider.when('/login', {
            templateUrl: 'components/login/partials/login.html',
            resolve: {
                load: ['$q', '$rootScope', function ($q, $rootScope) {

                    var deferred = $q.defer();

                    // lazy load controllers, etc.
                    require ([
                        'components/login/controllers/loginController',
                        'components/login/services/loginService'
                    ], function () {

                        $rootScope.$apply(function () {
                            deferred.resolve();
                        });

                    });

                    return deferred.promise;
                }]
            }
        });


        //store a reference to various provider functions
        window.app.components = {
            controller: $controllerProvider.register,
            service: $provide.service
        };

    }
]);

Now inside your loginController for instance you write

app.components.controller('loginController');

to define your new controller lazily.

If you want to lazy-load your templates too I recommend to use the ui-router. There you can specify a templateProvider which is basically a function to load templates async

This is a quote from https://github.com/webpack/webpack/issues/150

webpack is a module bundler not a javascript loader. It package files from local disk and don't load files from the web (except its own chunks).

Use a javascript loader, i. e. script.js

var $script = require("scriptjs");
$script("//ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js", function() {
  // ...
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!