背景:
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没有正常运行。
请问这是为什么呢?
自己折腾了一下,发现了以下内容:
几点发现
ES6的导出机制与commonjs的模块导出机制不同
ES6的
export default
导出的模块,在webpack中require
进来后是一个具有default
属性的对象;若使用import
得到结果与导出一致module.exports
导出的模块require
得到结果与导出一致$ocLazyLoad.load({name: moduleName})
来加载模块,当直接写字符串$ocLazyLoad.load(moduleName)
时好像会被认为是文件(这部分还有待确定,具体可以扒 oclazyload 的源码)方案概括
ES6 export default
+require
,使用layoutsModule.default
(非default
请根据导出名提取)ES6 export
+ES6 import
,使用layoutsModule
module.exports
+require
,使用layoutsModule
代码如下