angular2如何按需加载?

时间:2021-07-19 19:26:49

angular2用webpack打包每次都只打包成单个mian文件,很大,例如页面中的关于我们,联系我们这样的页面,用户可能几乎不会打开,但是我们还是每次都要让用户加载,体验很不好,

这样就需要按需加载,当不长访问的页面,我们就单独打包成一个页面,当客户访问时,再去加载JS文件。

那么angular2如何进行按需加载呢?

我们使用webpack-toolkit,可以直接在git上看教程https://github.com/AngularClass/webpack-toolkit

angular2自己也支持异步加载,可以查看AsyncRoute的使用,github上查找会有很多使用例子 

我写了个小demo,可以在dev分支中查看相关内容,https://github.com/lyt308012546/ng2-webpack-demo/tree/dev

 

// Install
npm install @angularclass/webpack-toolkit --save-dev


// app/about/about.ts

@Component({
  selector: 'about',
  template: '<h1>About</h1>'
})
export class About {}

// app/app.routes.ts

export const routes = [
  { path: '', component: Home },
  { path: 'about', component: 'About' }
];

// main.browser.ts

import {routes} from './app/app.routes';
import { provideWebpack } from '@angularclass/webpack-toolkit';
bootstrap(App, [
  provideRouter(routes),
  provideWebpack({
    'About': require('es6-promise!./app/about')
  })

]);

 

// 以下是采用AsyncRoute进行异步加载

import { Component } from '@angular/core';
import { RouteConfig, RouterOutlet ,AsyncRoute } from '@angular/router-deprecated';
import { Router } from '@angular/router-deprecated';

import { SubRouteComponent }   from './subroute';

@Component({
    template:  `
    <h2>RouteConfig Demo</h2>
    <button (click)="gotoDetail()">跳转</button>
    <router-outlet></router-outlet>
  `,
    directives: [RouterOutlet],
})
@RouteConfig([
    {path: '/',    name: 'SubRouteComponent',   component: SubRouteComponent, useAsDefault: true},
    // 异步按需加载
    new AsyncRoute({ path: '/detail', loader: () => require('es6-promise!./routedetail')('RouteDetailComponent'), name: 'RouteDetailComponent' }),
])
export class RouteDemo {

    constructor(
        private router: Router) {}

    gotoDetail(){
        this.router.navigate(['RouteDetailComponent']);
    }
}