我正在寻求有关使用 webpack 的帮助对于大型 AngularJS 应用程序。我们使用基于功能的文件夹结构(每个功能/页面都有一个模块,它们有 Controller 、指令)。我已成功配置 webpack 使其与 Grunt 一起工作,后者生成一个单独的包。我想创建 block ,因为它将成为一个大型应用程序,我们想异步加载模块(页面/功能)工件。
我正在通过一些 webpack 示例来使用 'code splitting'
使用 require([deps],fn )
语法。但是我无法延迟加载这些 block 。首先,我不知道确切的位置,我需要在 AngularJS 将用户路由到下一页之前导入这些 block 。我正在努力寻找明确的责任分工。
是否有人向我指出了一个示例 AngularJS 应用程序,其中 webpack 用于在每个路由后异步加载 Controller /指令/过滤器?
我关注的链接很少: Should I use Browserify or Webpack for lazy loading of dependancies in angular 1.x https://github.com/petehunt/webpack-howto#9-async-loading http://dontkry.com/posts/code/single-page-modules-with-webpack.html
最佳答案
Sagar Ganatra 写了一篇有用的文章 blog post关于代码拆分。
令人惊讶的是,angular 的模块系统并不真正支持代码拆分。但是,有一种方法可以通过在配置阶段保存对 Angular 特殊提供程序的引用来实现代码拆分。
[...] when Angular initializes or bootstraps the application, functions - controller, service etc,. are available on the module instance. Here, we are lazy loading the components and the functions are not available at a later point; therefore we must use the various provider functions and register these components. The providers are available only in the config method and hence we will have to store a reference of these providers in the config function when the application is initialized.
window.app.config([
'$routeProvider',
'$controllerProvider',
'$compileProvider',
'$filterProvider',
'$provide',
function ($routeProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
$routeProvider.when('/login', {
templateUrl: 'components/login/partials/login.html',
resolve: {
load: ['$q', '$rootScope', function ($q, $rootScope) {
var deferred = $q.defer();
// lazy load controllers, etc.
require ([
'components/login/controllers/loginController',
'components/login/services/loginService'
], function () {
$rootScope.$apply(function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
});
//store a reference to various provider functions
window.app.components = {
controller: $controllerProvider.register,
service: $provide.service
};
}
]);
现在在你的 loginController
中你写的例子
app.components.controller('loginController');
懒惰地定义你的新 Controller 。
如果你也想延迟加载你的模板,我建议使用 ui-router .在那里你可以指定一个 templateProvider
这是 basically a function to load templates async
关于javascript - AngularJS 和 Webpack 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26477228/