각도 지연 로드 실현

Angular 애플리케이션이 로드되면 모든 애플리케이션 모듈이 반드시 필요한지 여부에 관계없이 로드됩니다.현재 응용 프로그램이 매우 작으면 큰 문제가 되지 않을 수도 있지만, 모듈이 최종적으로 증가함에 따라 전체 응용 프로그램의 속도를 떨어뜨릴 것이다.
이 문제의 답은 로드 지연을 통해 나온 것이다. 이런 기술은 처음에는 필요한 모듈만 로드하고 실제 필요할 때만 다른 모듈을 로드한다.
official docs부터,

By default, NgModules are eagerly loaded, which means that as soon as the application loads, so do all the NgModules, whether or not they are immediately necessary. For large applications with lots of routes, consider lazy loading—a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.


로드 지연의 이점


로드 지연은 필요할 때 리소스를 로드하므로 다음과 같은 결과가 발생합니다.
  • 빠른 로드 속도
  • 더 나은 사용자 환경
  • 대역폭 절감
  • 이제 로드 지연의 작용을 살펴봅시다.

    로드 지연 실현


    Angular 응용 프로그램 만들기


    먼저 Angular CLI를 사용하여 Angular 애플리케이션을 생성합니다.
    ng new angular-app
    
    예를 들어, yes 각도 경로설정을 생성하고 CSS 스타일시트 형식을 추가합니다.
    응용 프로그램을 만든 후 프로젝트 디렉토리로 이동하여 응용 프로그램을 실행합니다.
    cd angular-app
    npm start
    
    Angular 프로그램이 시작되고 실행되는 것을 볼 수 있습니다.
    우리의 응용 프로그램에는 두 개의 모듈, 계기판 모듈과 가정 모듈이 있을 것이다.기본적으로 응용 프로그램 모듈을 불러옵니다.응용 프로그램 모듈에서 링크를 클릭하면 홈 모듈과 대시보드 모듈이 그림에 나타납니다.

    대시보드 모듈 만들기


    응용 프로그램 루트 디렉토리에서 다음 명령을 실행하여 대시보드 모듈을 생성합니다.
    ng g module dashboard --routing
    
    위의 명령은 대시보드 모듈을 만듭니다.--routing 옵션은 모듈에 대한 라우팅 구성을 생성합니다.모듈 명령을 실행하면 응용 프로그램src/app 폴더를 검사할 수 있습니다. 이 폴더는 대시보드 모듈dashboard 폴더를 포함합니다.폴더에는 모듈별 라우팅에 사용되는 dashboard-routing.module라는 파일도 있습니다.
    이제 dashboard module 폴더로 이동하여 이 모듈에 구성 요소를 만듭니다.
    cd .\src\app\dashboard\
    ng g component chart
    
    dashboard-routing.module 구성 요소를 가리키는 모듈의 기본 루트를 추가하여 Chart 파일을 수정합니다.다음은 파일의 모양입니다.
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { ChartComponent } from './chart/chart.component';
    
    const routes: Routes = [
      {path: '', component: ChartComponent},
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })
    export class DashboardRoutingModule { }
    
    다음 HTML을 chart.component.html 파일에 추가합니다.
    <h4>
        Welcome Dashboard
    </h4>
    

    Home 모듈 만들기


    Home 모듈을 만듭니다.프로젝트 루트 디렉토리에서 다음 명령을 실행합니다.
    ng g module home --routing
    
    위의 명령은 루트 설정이 있는 주 모듈을 만듭니다.
    주 모듈 폴더로 이동하여 주 모듈 안에 구성 요소를 만듭니다.
    cd .\src\app\home\  
    ng g component userHome
    
    파일home-routing.module.ts을 수정하고 기본 라우트를 UserHomeComponent로 설정합니다.다음은 home-routing.module.ts 파일입니다.
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { UserHomeComponent } from './user-home/user-home.component';
    
    const routes: Routes = [
      {path: '', component: UserHomeComponent},
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })
    export class HomeRoutingModule { }
    
    다음 HTML을 user-home.component.html 파일에 추가합니다.
    <h4>
        Welcome Home
    </h4>
    
    app.component.html 파일에 다음 HTML을 추가합니다.
    <h2>
      Welcome to course !!
    </h2>
    <a [routerLink]="'home'">Go to Home</a>
    <a [routerLink]="'dashboard'">Dashboard</a>
    <router-outlet></router-outlet>
    

    로드 지연 없음


    부품 참조를 app.module.ts 파일에 추가하려면 다음과 같이 하십시오.
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { ChartComponent } from './dashboard/chart/chart.component';
    import { UserHomeComponent } from './home/user-home/user-home.component';
    
    @NgModule({
      declarations: [
        AppComponent,
        ChartComponent,
        UserHomeComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    원하는 라우트를 app-routing.module.ts 파일에 추가하려면 다음과 같이 하십시오.
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { ChartComponent } from './dashboard/chart/chart.component';
    import { UserHomeComponent } from './home/user-home/user-home.component';
    
    const routes: Routes = [
      {path: 'dashboard', component: ChartComponent},
      {path: 'home',component : UserHomeComponent}
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    
    위 그림Routes에서 보듯이 /dashboard에 대한 요청은 ChartComponent에 있는 DashboardModule, /home 노선에 대한 요청은 UserHomeComponent에 있습니다.
    위의 변경 사항을 저장하고 각도 응용 프로그램을 시작합니다.기본 페이지에는 각각 홈 페이지와 대시보드에 대한 두 개의 링크가 표시됩니다.이 두 링크 중 하나를 클릭하면 해당 모듈로 안내해 줍니다.

    콘솔을 보면 볼 수 있는 파일 크기main.js가 15.4KB입니다.이것은 불러오는 모든 구성 요소 데이터입니다.만약 주의하신다면, 우리는 처음 불러올 때 계기판 모듈과 메인 모듈을 사용할 필요가 없습니다.너는 그들의 특정 링크를 클릭하기만 하면 된다.
    이제 지연 로드를 어떻게 사용해서 이 점을 실현하는지 봅시다.

    로드 지연


    로드 모듈을 지연하려면 app-routing.module.ts 파일로 이동하여 사용하십시오loadChildren.app-routing.module.ts에서 모듈을 가져올 필요는 없지만 실행할 때 동적으로 가져옵니다.
    다음은 app-routing.module.ts 파일의 모양입니다.
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    
    const routes: Routes = [
      {path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule)},
      {path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)}
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    
    app.module.ts를 수정하여 Chart 구성 요소와 UserHome 구성 요소 가져오기를 삭제합니다.
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { } 
    
    변경 사항을 저장하고 프로그램을 불러옵니다.이제 초기 로드 시 브라우저 콘솔을 확인하면 main.js 크기가 11.4KB로 줄어듭니다.

    링크를 클릭하면 모듈 파일이 필요에 따라 불러오는 것을 볼 수 있습니다.빨간색으로 표시된 파일을 확인하십시오.처음 적재했을 때 그것은 거기에 없었다.

    결론


    로드 지연은 필요한 파일만 먼저 로드하기 때문에 초기 로드 시간을 줄이는 데 도움이 되는 중요한 각도 특성입니다.필요한 다른 모듈의 특정 노선을 탐색하면 필요에 따라 불러옵니다.
    현재, 당신은 이 기능을 이용하여 프로그램의 불러오는 시간을 높일 수 있다.마지막으로, 만약 당신이 Angular 소스 코드를 도난과 역방향 프로젝트로부터 보호하는 방법을 배우고 싶다면, 반드시 검사해야 한다.
    이 강좌의 원본 코드는 GitHub에서 얻을 수 있습니다.

    좋은 웹페이지 즐겨찾기