Angular 2和Webpack延迟加载

前端之家收集整理的这篇文章主要介绍了Angular 2和Webpack延迟加载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我肯定错过了一些非常基本的东西.我正在开发一个用户登录的Angular 2应用程序.登录后,用户将能够访问仅对登录用户可见的安全组件.如何分离Webpack以首先提供登录屏幕,并且只有在成功登录其余部分之后?

angular2-authentication-sample的chrome dev工具中,我可以在登录前看到所有的源代码.甚至是登录后才能看到的页面的源代码.

所以我的问题是:

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

解决方法

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

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中,并使用3rd parameter将此块命名为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文件.

猜你在找的Angularjs相关文章