Angular 2和Webpack延迟加载



我肯定遗漏了一些非常基本的东西。我正在开发一个用户登录的Angular 2应用程序。登录后,用户将能够访问只有登录用户才能看到的安全组件。我如何将Webpack分离为首先提供登录屏幕,只有在成功登录后才提供其余屏幕?

在chrome-dev工具中的angular2身份验证示例中,我可以在登录前看到所有的源代码。甚至只有在登录后才可见的页面的源代码也可以。

所以我的问题是:

  • 限制用户访问登录屏幕后面部分的源代码的正确方法是什么

您可以使用动态加载块的功能。例如,想象一下这个路由模型:

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: '/'
},

网络包将生成以下文件:

main.js
1.protected.js

现在,您必须在备份上提供自己的保护-不向未通过身份验证的用户发送*.protected.js文件

如果您不希望所有代码都在客户端,您可以使用以下内容:

角度通用

Angular Universal启动器

Angular Universal Github页面

最新更新