我肯定在这里遗漏了一些非常基本的东西。我正在开发一个用户登录的 Angular 2 应用程序。登录后,用户将能够访问仅对登录用户可见的安全组件。我怎样才能将 Webpack 分开以首先为登录屏幕提供服务,只有在成功登录后才剩下?
在angular2-authentication-sample在 chrome 开发工具中,我可以在登录前看到所有源代码。即使是只有在登录后才能看到的页面的源代码。
所以我的问题是:
- 限制用户访问登录屏幕后面部分的源代码的正确方法是什么。
最佳答案
您可以使用动态加载 block 的强大功能。例如,想象一下这个路由模型:
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
的力量.使用 3rd parameter 在 require.ensure
中包装您的 protected 路由将此 block 命名为 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
文件。
关于Angular 2 和 Webpack 延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38426625/