I am surely missing something very fundamental here. I am developing an Angular 2 app where the user logs in. After login the user will be able to access secured components that are only visible to logged in users. How can i seperate Webpack to first serve the login screen and only after a succesfull login the rest?
In angular2-authentication-sample in chrome dev tools I can see all the source code before logged in. Even the source code of the pages that are visible only after login.
So my question is:
You can use power of dynamically loaded chunks. For example imagine this mockup of routing:
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 above example all your routes will be downloaded in single bundle.js
file. To change that you can use power of require.ensure
. Wrap your protected routes in require.ensure
with 3rd parameter naming this chunk as protected
(this name can be different - it's just 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 your webpack.config.js
if you will have this configuration:
entry: path.resolve('src', 'main.js'),
output: {
path: path.resolve('build'),
filename: '[name].js', // <-- this is important
publicPath: '/'
},
The webpack will produce this files:
main.js
1.protected.js
Now you must provide on your own protection on the backed - to not send *.protected.js
file for not authenticated users .
If you do not want all of your code to be on the client side, you can use something like:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.