我肯定错过了一些非常基本的东西.我正在开发一个用户登录的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: '/' },
main.js 1.protected.js