[英]Angular 2 and Webpack lazy loading
我肯定在这里错过了一些非常基本的东西。 我正在开发用户登录的Angular 2应用程序。登录后,用户将能够访问仅对登录用户可见的安全组件。 我怎样才能分开Webpack来首先为登录屏幕提供服务,而只有在成功登录后再提供其余服务?
在chrome开发工具中的angular2-authentication-sample中,我可以在登录之前查看所有源代码。即使只有登录后才可见的页面源代码。
所以我的问题是:
您可以使用动态加载的块的功能。 例如,想象一下这个路由模型:
switch(routeName) {
case 'home':
const homePage = require('homePage');
homePage();
break;
case 'contact':
const contactPage = require('contactPage');
contactPage();
break;
case 'dashboard': // <-- this should be protected
const dashboardPage = require('dashboardPage');
dashboardPage();
break;
case 'informationForLoggedUser': // <-- this should be protected
const informationForLoggedUserPage = require('informationForLoggedUserPage');
informationForLoggedUserPage();
break;
};
在上面的示例中,所有路由都将下载到单个bundle.js
文件中。 要进行更改,可以使用require.ensure
。 将受保护的路由包装在require.ensure
并使用第三个参数将此块命名为protected
(此名称可以不同-只是示例)。
switch(routeName) {
case 'home':
const homePage = require('homePage');
homePage();
break;
case 'contact':
const contactPage = require('contactPage');
contactPage();
break;
case 'dashboard': // <-- this will be protected
require.ensure([], () => {
const dashboardPage = require('dashboardPage');
dashboardPage();
}, 'protected');
break;
case 'informationForLoggedUser': // <-- this will be protected
require.ensure([], () => {
const informationForLoggedUserPage = require('informationForLoggedUserPage');
informationForLoggedUserPage();
}, 'protected');
break;
};
在webpack.config.js
如果您具有以下配置:
entry: path.resolve('src', 'main.js'),
output: {
path: path.resolve('build'),
filename: '[name].js', // <-- this is important
publicPath: '/'
},
Webpack将产生以下文件:
main.js
1.protected.js
现在,您必须在支持上提供自己的保护-不会为未经身份验证的用户发送*.protected.js
文件 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.