我当前在项目中使用了Angular 1.5,我的路由看起来像这样:
const routes = ($stateProvider) => {
$stateProvider
.state('update', {
url: '/update',
template: '<update></update>',
resolve: {
lazyload: [ '$q', '$ocLazyLoad', function ($q, $ocLazyLoad) {
console.log('start lazy');
let deferred = $q.defer();
require.ensure([], function () {
let module = require('../components/update/update.module');
let module = require('../components/update/update.module');
$ocLazyLoad.load({
name: module.default.name
});
deferred.resolve(module);
});
return deferred.promise;
}
]
}
})
.state('login', {
url: '/login',
template: '<login></login>',
resolve: {
lazyload: [ '$q', '$ocLazyLoad', function ($q, $ocLazyLoad) {
let deferred = $q.defer();
require.ensure([], function () {
let module = require('../components/login/login.module');
$ocLazyLoad.load({
name: module.default.name
});
deferred.resolve(module)
});
return deferred.promise;
}
]
}
});
};
当我尝试在这样的单独函数中提取重复代码时:
function load (modulePath) {
return function ($q, $ocLazyLoad) {
let deferred = $q.defer();
require.ensure([], function () {
let module = require(modulePath);
$ocLazyLoad.load({
name: module.default.name
});
deferred.resolve(module);
});
return deferred.promise;
}
}
并以这种方式使用负载函数:
$stateProvider
.state('update', {
url: '/update',
template: '<update></update>',
resolve: {
lazyload: [ '$q', '$ocLazyLoad', load('../components/update/update.module')]
}
})
该路由不再起作用,我会收到此错误"找不到模块"。
使用动态要求时,请勿在参数中包括路径和扩展。
将所有懒惰模块都需要放在单独的文件夹lazy
中。
function load (state) {
return function ($q, $ocLazyLoad) {
let deferred = $q.defer();
require.ensure([], function () {
let module = require('../components/lazy/' +state+ '.module');
$ocLazyLoad.load({
name: module.default.name
});
deferred.resolve(module);
});
return deferred.promise;
}
}
$stateProvider
.state('update', {
url: '/update',
template: '<update></update>',
resolve: {
lazyload: [ '$q', '$ocLazyLoad', load('update')]
}
})
您可以使用与建议的结构不同的结构。请参阅https://webpack.github.io/docs/context.html#dynamic-requires