It can be optimized from the following four perspectives:

  1. Lazy loading of modules
  2. Output package composition analysis file
  3. Rollup Tree shaking optimization
  4. Export the Webpack configuration to optimize packaging by modifying the Webpack configuration

Let’s break it down one by one.

Lazy loading of modules

By default, all routes are loaded at initialization. So many pages are loaded at once, resulting in very slow page loading. Angular uses lazy loading to load.

Generally speaking, it means that when entering the main module, the submodule is not loaded, and when it needs to enter the submodule, it is loaded. When dividing project modules, using loadChildren to configure routing is the best option.

Key knowledge points

  1. RouterModule. ForRoot () and RouterModule forChild ()

    The RouterModule object provides two static methods, forRoot() and forChild(), to configure routing information.

    The RouterModule.forroot () method is used to define the main routing information in the main module. Routermodule.forchild () is similar to router.forroot (), but only applies to feature modules (submodules).

    That is, forRoot() is used in the root module and forChild() is used in the submodule.

  2. Lazy loading: loadChildren

    The lazy LoadChildren property is used here. Instead of importing the module into the AppModule, the loadChildren attribute tells Angular to load the module along the path specified by the loadChildren attribute. This is the specific application of the lazy loading function when the user accesses/XXX /**

    Path, the corresponding module will be loaded, which reduces the amount of resources to load when the application starts.

    The loadChildren attribute value consists of three parts:

    1). Relative path of the module to be imported

    2). # delimiter

    3). Export the module class name

Lazy loading implementation

1. Create projects
Ng new angularLaod --routing (generate projects with routing Modules by default)Copy the code
Routing performs the following steps: 1. Create app-routing.module.ts 2. Import app-routing.module.ts to app.module.ts 3. Add <router-outlet></router-outlet> to app.component.htmlCopy the code
2. Generate submodules
ng g m childrenLaod --routing
Copy the code
3. Declare a component in a component
ng g c children-load/child
Copy the code
Add the default route path to children-load-routingCopy the code
import {ChildComponent} from './child/child.component';

const routes: Routes = [
	{path:' ',component:ChildComponent}
];
Copy the code
Repeat steps 2, 3, and 4 to generate children-newLoadCopy the code
4. Import the children-load module in the app-routing.module
const routes: Routes = [
  {path:' ',redirectTo:'child'},
  {path:'child',loadChildren:'./children-load/children-load.module#ChildrenLoadModule'},
  {path:'childNew',loadChildren:'./children-newload/children-newload.module#ChildrenNewloadModule'}];Copy the code
Note: # LoadChildren must follow relative path + + name of the module (reference: https://blog.csdn.net/idomyway/article/details/84996458)Copy the code

Output package composition analysis file

Webpack has a very useful tool called WebPack-bundle-Analyzer that automatically analyzes the package structure and displays it in a visual way.

Use steps:

  1. Open the project and type from the command line:npm install webpack-bundle-analyzer --save-dev
  2. Command line input project package command plus--stats-json
  3. In the “scripts” configuration of package.json file, add"bundle-report": "webpack-bundle-analyzer dist/wp/stats.json"
  4. Command line input:npm run bundle-report
  5. Enter http://127.0.0.1:8888/ in your browser to view the analysis chart and learn some optimization details

In the process of viewing the analysis chart, I found the following points:

  1. In does not affect the performance of the case, use less as far as possible Base64 introduction pictures, introduce the image on the local, not packaged into the project, but using Base64 encoded picture, the picture will be 1.5 times the volume of packaging in the project, and if the image is fairy figure, using pictures taken div cut figure, cut several times, will pack a few times, The occupancy volume is very large. You can refer to the following in detail: www.imooc.com/article/278…

  2. Use import to introduce dependencies instead of require. Here’s why:

    The core concept of require is to define module.exports in an exported file. The exported object type is unqualified (it can be any type). Use the require() import in the imported file.

    Essentially, the exported object is assigned the exports property of the module object, which is accessed through the require method in other files. Sys = exports; require(./a. exports) = exports; es6 = test;

    Import is a new syntax introduced in ES6 for JS modularity. Import is used in conjunction with export.

    Commonjs modules differ from ES6 modules:

    (1). Commonjs outputs a copy of a value, while es6 outputs a reference to a value;

    (2).commonJS is run time loading, es6 is compile time output interface.

    Please refer to: blog.csdn.net/liya_nan/ar…

Rollup Tree shaking optimization

Rollup refers to the fact that Webpack2 removes references that are not used in the application, but does not remove them, so UglifyJs can intelligently remove the unused code. Thus reducing the inclusion size.

Agnular applications are based on Typescript, so the Angular Cli provides a plugin called Angular Build Optimizer that converts Typescript compilations into a friendlier version of UglifyJs. This allows UglifyJs to remove unused code more efficiently

Method 1: The Angular Cli simply adds the — build-Optimizer parameter to the package command. In some cases, the compression is still quite severe (but it didn’t work when I used this method for optimization).
Method 2: Remove unused modules to reduce volume (this method has no effect on my optimized project)
  1. moment

    • For ng-CLI projects:

      (1) Run NPM uninstall moment

      (2) Run NPM install moment –save-dev

      (3).angular-cli.json file scripts add “.. /node_modules/moment/min/moment.min.js”

      Typings.d. ts declare var moment: any;

      (5) import code from the project * as moment from ‘moment’; All kill

      Note: Required if you want to apply one of these libraries (for example fr)

      Import “moment/locale/fr”;

      Use: my moment. Locale (” fr “);

    • For webpack projects:

      (1) Add it to plugins in the WebPack configuration file

      New webpack. ContextReplacementPlugin (/ moment [\ / \ \] locale $/, / /) or

      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)

      Note: If you want to use one of these libraries, you need to add it to plugins in the WebPack configuration file (for example, de, FR, hu)

      new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /de|fr|hu/)

    Remark:

    I did some research and learned that if you only use the moment method in your project, you can import it on demand, and if you use the moment instance object, you can only import the whole moment object.

  2. @ng-bootstrap/ng-bootstrap

    If you use the @ng-bootstrap/ng-bootstrap library in your project, be careful how you use it. If you use the @ng-bootstrap/ng-bootstrap library in your project, it will include all of its modules in the package, whether you use them or not. So find a way to eliminate the modules you don’t need and only introduce the ones you need.

    Take the time component as an example.

    // Import {NgbModule} from'@ng-bootstrap/ng-bootstrap'; @NgModule({ declarations: [AppComponent, ...] , imports: [NgbModule.forRoot(), ...] , bootstrap: [AppComponent] })export class AppModule {
    }
    Copy the code
    // Other required modules import {NgbModule} from'@ng-bootstrap/ng-bootstrap'; @NgModule({ declarations: [OtherComponent, ...] , imports: [NgbModule, ...] ,})export class OtherModule {
    }
    Copy the code

    Changed to:

    // Import {NgbDatepickerModule, NgbTimepickerModule} from'@ng-bootstrap/ng-bootstrap'; @NgModule({ declarations: [AppComponent, ...] , imports: [NgbDatepickerModule.forRoot(), NgbTimepickerModule.forRoot() ...] , bootstrap: [AppComponent] })export class AppModule {
    }
    Copy the code
    Import {NgbDatepickerModule, NgbTimepickerModule} from'@ng-bootstrap/ng-bootstrap'; @NgModule({ declarations: [OtherComponent, ...] , imports: [NgbDatepickerModule, NgbTimepickerModule, ...] ,})export class OtherModule {
    }
    Copy the code

Export the Webpack configuration

Method 1: Eject (Angular6 might not support it)
Method 2: Tool library NGX-build-Plus

I expect to separate the SCSS file from the main.js package by exporting the Webpack configuration, still in practice, success will follow.

Reference article:

  1. www.mamicode.com/info-detail…
  2. www.imooc.com/article/278…
  3. Blog.csdn.net/liya_nan/ar…