javascript - 在路由的resolve中使用lazyload加载控制器无效
巴扎黑
巴扎黑 2017-04-11 09:53:22
0
1
543

背景:
webpack打包
angular-ui-router配置路由
angular1.4.7
ocLazyLoad

// ../layouts/layouts.controller.js       
export default function layoutsController($scope) {
    'ngInject';
    console.info('layoutsController:', 'controller is loaded');
}
// ../layouts/index.js
import layoutsController from './layouts.controller.js';

let layoutsModule = angular
    .module('layouts', [])
    .controller('layoutsController', layoutsController);
    
export default layoutsModule.name;
//写法1
$stateProvider
        .state('app', {
            url: '/app',
            template: require('./views/app.html'),
            controller: 'layoutsController as vm',
            resolve: {
                loadLayoutsController: function($q, $ocLazyLoad) {
                    console.info('state resolve:', 'app, layoutsController');
   
                    var deferred = $q.defer();
                    let layoutsModule = require('../layouts');
                    $ocLazyLoad.load(layoutsModule);
                    deferred.resolve();
                    return deferred.promise;
                }
            }
        });
       
//写法2       
$stateProvider
        .state('app', {
            url: '/app',
            template: require('./views/app.html'),
            controller: 'layoutsController as vm',
            resolve: {
                loadLayoutsController: function($ocLazyLoad) {
                    console.info('state resolve:', 'app, layoutsController');
                    let layoutsModule = require('../layouts');
                    return $ocLazyLoad.load(layoutsModule); 
                }
            }
        });

采用写法1时能够正常打出
console.info('state resolve:', 'app, layoutsController');
console.info('layoutsController:', 'controller is loaded');两条信息
采用写法2时只能够正常打出
console.info('state resolve:', 'app, layoutsController');一条信息,layoutsController没有正常运行。

请问这是为什么呢?

巴扎黑
巴扎黑

reply all(1)
洪涛

自己折腾了一下,发现了以下内容:

几点发现

  1. ES6的导出机制与commonjs的模块导出机制不同

  2. ES6的export default导出的模块,在webpack中require进来后是一个具有default属性的对象;若使用import得到结果与导出一致

  3. module.exports导出的模块require得到结果与导出一致

  4. $ocLazyLoad.load({name: moduleName}) 来加载模块,当直接写字符串$ocLazyLoad.load(moduleName)时好像会被认为是文件(这部分还有待确定,具体可以扒 oclazyload 的源码)

方案概括

  • ES6 export default+require,使用layoutsModule.default(非default请根据导出名提取)

  • ES6 export+ES6 import,使用layoutsModule

  • module.exports+require,使用layoutsModule

代码如下

let layoutsModule = require('../layouts').default;
// or
import layoutsModule from '../layouts';

resolve: {
    loadLayoutsController: function($ocLazyLoad) {
        return $ocLazyLoad.load({name: layoutsModule}); 
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template