使用browserify以角度延迟加载组件

时间:2015-04-23 05:53:42

标签: javascript angularjs browserify

我正在概述基于角度的相当复杂的应用程序的架构。所以我开始使用角度种子项目,这似乎是一个很好的起点。困扰我的是,角度应用程序本质上涉及到前期加载所有内容。使用脚本加载器,似乎没有一个干净的方法。

我来自backbone.js背景,并且在那里很安静直接使用require.js进行基于路由器回调的延迟加载。角度路线在某种程度上定义如下:

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.when({templateURL:'../tmpl.html',controller:'view1Ctrl'})
.when({templateURL:'../tmpl.html',controller:'view1Ctrl'})
.otherwise({redirectTo: '/view1'});
}]);

现在在这里,$routeProvider.when({templateURL:'../tmpl.html',controller:'view1Ctrl'})我想懒洋洋地加载控制器和模板。我很想使用类似的东西:

$routeProvider.when({templateURL:'../tmpl.html',controller:require('view1Ctrl'})

使用browserify但是它似乎并不干净,甚至没有要求。我知道这个问题在某些方面已被问过几次,但我没有找到一个有力的答案。

我的偏好是使用browserify,因为它支持浏览器中备受喜爱的cjs模块。

1 个答案:

答案 0 :(得分:3)

我不确定如何使用Browserify执行此操作,因为我自己从未尝试过,但我强烈建议您查看ocLazyLoad

作为一个独立的服务,它可以创建加载文件(json,css,js,模板 - 您的名字)并将其注入已经运行的角度应用程序中。

话虽如此,它可以更好地(imo)与路由器(默认的角度路由器或ui路由器)配合使用。

有一些种子项目'这展示了如何使用ocLazyLoad和SystemJS来实现它。

但你甚至不需要那样。

如果你使用ui-router,ui-router-extras和ocLazyLoad,你可以把这样的东西放到懒惰的负载状态:

<强> main.js

/** 
 * Inject the needed dependencies into our main module.
 */
var main = angular.module('main', [ 'ui.router', 'ct.ui.router.extras.future', 'oc.lazyLoad' ]);

/**
 * Define the lazy loaded states.
 */
main.constant('lazyLoadedStates', [
  {
    name: 'about',
    url:  '/about',
    type: 'lazy',
    src: [
      '/path/to/about.module.js',
      '/path/to/AboutController.js'
    ]
  }
]);

/**
 * Setup the behaviour for when we hit a futureState with the 'lazy'
 * type. 
 * 
 * 1. Setup a deferred object.
 * 2. Resolve the promise when every file defined in the futureState.src has been loaded.
 * 3. Return the promise.
 */
main.config(function ($futureStateProvider, lazyLoadedStates) {
  $futureStateProvider.stateFactory('lazy', function ($q, $ocLazyLoad, futureState) {
    var deferred = $q.defer();

    $ocLazyLoad.load(futureState.src).then(function () {
      deferred.resolve();
    });

    return deferred.promise;
  });

  lazyLoadedStates.forEach($futureStateProvider.futureState);
});

那个&#39;框架&#39; - 现在你只需要继续添加更多模块,使用更多代码,并将真实状态定义与{{1>}中的虚拟状态定义相匹配不变。

<强> about.module.js

lazyLoadedStates

<强> AboutController.js

/** 
 * Setup the _real_ '/about' state in this lazy loaded file.
 */
angular.module('about', []).config(function ($stateProvider) {
  $stateProvider.state('about', {
    url: '/about',
    controller: 'AboutController',
    template: 'some_template.html'
  });
});

我希望能让您大致了解如何在Angular中设置延迟加载状态。我还没有找到一种更简单的方法来做到这一点,但我确定那里有关于如何将ui-router(或默认的角度路由器)与其他一些“lazy-loader”结合起来的文章#39 ;。

文档链接:

相关问题