Angular 2 and Webpack lazy loading

Of course, I am missing something very important. I am developing an Angular 2 application where a user logs in. After logging in, the user will be able to access protected components that are visible only to the system. How can I separate Webpack to serve the login screen first, and only after a successful login?

In angular2-authentication-sample in chrome dev tools I see all the source code before logging in. Even the source code of pages that are visible only after logging in.

So my question is:

  • What is the correct way to restrict user access to the source code of the section that is located behind the login screen.
+4
source share
2 answers

You can use the power of dynamically loaded pieces. For example, imagine this routing layout:

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;
};

In the above example, all your routes will be loaded into one file bundle.js. To change this, you can use force require.ensure. Wrap protected routes in require.ensurewith the third parameter , naming this fragment as protected(this name may be different - this is just an example).

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;
};

In yours webpack.config.js, if you have this configuration:

entry: path.resolve('src', 'main.js'),
output: {
  path: path.resolve('build'),
  filename: '[name].js',       // <-- this is important
  publicPath: '/'
},

The web package will create these files:

main.js
1.protected.js

Now you must provide your own protection on the backup — do not send the *.protected.jsfile to unauthenticated users .

+3
source

Source: https://habr.com/ru/post/1648182/


All Articles