Skip to content
Dan Thareja edited this page Oct 7, 2015 · 3 revisions

With the help of webpack and ocLazyLoad, you can easily bundle your app by component, loading only what is needed when it is needed.

Consider an adapted about.js

import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ocLazyLoad from 'oclazyload';

let aboutModule = angular.module('about', [
  uiRouter,
  ocLazyLoad
])

.config(($stateProvider, $compileProvider) => {
   $stateProvider
    .state('about', {
      url: '/about',
      template: '<about></about>',

      // Lazy load this component
      resolve: {
        loadComponent: ($q, $ocLazyLoad) => {
          var deferred = $q.defer();

          // Webpack will define a code-split point for all requires in this callback
          // This will effectively bundle this entire module into a single file
          // that only gets downloaded when this state is transitioned to
          require.ensure([], function(require) {

            // Require our modules
            // This replaces the `import` statements from above
            let something = require('./about.something');
            // .. any other dependencies
            let component = require('./about.component');

            // Inject all dependencies into our module
            // This replaces adding them to the original angular.module dependency array
            $ocLazyLoad.inject([
              something.name
            // .. any other dependencies
            ])

            // Register the component so the template recognizes it
            .then(() => $compileProvider.directive('about', component))

            // Continue the state transition
            .then(deferred.resolve);

          }, 'about'); // Name our bundle so it shows up pretty in the network tab

          return deferred.promise
        }
      }
    });
});

export default aboutModule;
Clone this wiki locally