前言
本文形容如何正当拆分我的项目,对于性能优化等方面后续的文章再探讨。
Angular 让人诟病的一点就是打包后体积很大,一不小心 main.js
就大的离谱,其实遇到相似的问题,不论是体积大、数据大、还是流量大,就一个思路:拆分。再配合浏览器的缓存机制,能很好的优化我的项目访问速度。
本文相干代码在:https://github.com/Vibing/ang...
拆分思路
- 整个我的项目包含:强依赖库(Angular框架自身)、UI组件库及第三方库、业务代码局部;
- 用户行为维度:用户的所有拜访基于路由,一个路由一个页面;
从以上两点能够进行拆分,基于第 1 点能够把强依赖库和简直不会变动的库打包成一个 vendor_library
,外面能够蕴含@angular/common
、@angular/core
、@angular/forms
、@angular/router
等相似的包,UI组件库或lodash
这类库不倡议一起打包,因为咱们要使用 TreeShaking ,没必要把不必的代码也打包进来,否则只会减少体积。
强依赖包搞定了,上面基于第 2 点思路打包业务代码。咱们应用基于路由的 code spliting
来打包。思路很简略,用户拜访哪个页面,就把该页面对应的 js 下载下来,没必要把没拜访的页面一起打包,那样不仅造成体积增大,还会减少下载工夫,用户体验也会随之变差。
自定义webpack配置
咱们要想应用 DLL 将强依赖包打进一个 vendor 里就要应用 webpack 的性能,Angular CLI 中曾经内嵌了 webpack,但这些配置对咱们来说是黑盒子。
Angular 容许咱们自定义 webpack 配置,步骤如下
- 装置
@angular-builders/custom-webpack
和@angular-devkit/build-angular
- 新建一个 webpack.extra.config.ts 用于 webpack 配置
- 在 angular.json 中做如下批改
..."architect": { "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { ... "customWebpackConfig": { // 援用要拓展的 webpack 配置 "path": "./webpack.extra.config.ts", // 是否替换反复插件 "replaceDuplicatePlugins": true } } }, "serve": { "builder": "@angular-builders/custom-webpack:dev-server", "options": { "browserTarget": "angular-webpack:build" } } ...
应用DLL
能够自定义 webpack 配置后,新建 webpack.dll.js 文件来写 DLL 的配置:
const path = require("path");const webpack = require("webpack");module.exports = { mode: "production", entry: { vendor: [ "@angular/platform-browser", "@angular/platform-browser-dynamic", "@angular/common", "@angular/core", "@angular/forms", "@angular/router" ], }, output: { path: path.resolve(__dirname, "./dll"), filename: "[name].dll.js", library: "[name]_library", }, plugins: [ new webpack.DllPlugin({ context: path.resolve(__dirname, "."), path: path.join(__dirname, "./dll", "[name]-manifest.json"), name: "[name]_library", }), ],};
而后在 webpack.extra.config.ts 中进行 dll 引入
import * as path from 'path';import * as webpack from 'webpack';export default { plugins: [ new webpack.DllReferencePlugin({ manifest: require('./dll/vendor-manifest.json'), context: path.resolve(__dirname, '.'), }) ],} as webpack.Configuration;
最初在 package.json 中增加一条打包 dll 的命令:"dll": "rm -rf dll && webpack --config webpack.dll.js"
,执行 npm run dll
后在我的项目根部就会有 dll 的文件夹,外面就是打包的内容:
打包实现后,咱们要在我的项目中应用 vendor.dll.js
,在 angular.json
中进行配置:
"architect": { ... "build": { ... "options": { ... "scripts": [ { "input": "./dll/vendor.dll.js", "inject": true, "bundleName": "vendor_library" } ] } }}
打包后能够看到讲 vendor_library.js
曾经引入进来了:
DLL 的用途是将不会频繁更新的强依赖包打包合并为一个 js 文件,个别用于打包 Angular 框架自身的货色。用户第一次拜访时浏览器会下载 vendor_library.js
并会将其缓存,当前每次拜访间接从缓存里拿,浏览器只会下载业务代码的 js 而不会再下载框架相干的代码,大大晋升利用加载速度,晋升用户体验。
ps: vendor_library 前面的 hash 只有打包时外面代码有变动才会从新扭转 hash,否则不会变。
路由级CodeSpliting
DLL 把框架局部的代码治理好了,上面咱们看看如何在 Angular 中实现路由级别的页面按需加载。
这里打个岔,在 React 或 Vue 中,是如何做路由级别代码拆分的?大略是这样:
{ path:'/home', component: () => import('./home')}
这里的 home 指向的是对应的 component,但在 Angular 中无奈应用这种形式,只能以 module 为单位进行代码拆分:
{ path:'/home', loadChild: ()=> import('./home.module').then(m => m.HomeModule)}
而后在具体的模块中应用路由拜访具体的组件:
import { HomeComponent } from './home.component'{ path:'', component: HomeComponent}
尽管不能间接在 router 中 import()
组件,但 Angular 提供了组件动静导入的性能:
@Component({ selector: 'app-home', template: ``,})export class HomeContainerComponent implements OnInit { constructor( private vcref: ViewContainerRef, private cfr: ComponentFactoryResolver ){} ngOnInit(){ this.loadGreetComponent() } async loadGreetComponent(){ this.vcref.clear(); // 应用 import() 懒加载组件 const { HomeComponent } = await import('./home.component'); let createdComponent = this.vcref.createComponent( this.cfr.resolveComponentFactory(HomeComponent) ); }}
这样在路由拜访某个页面时,只有让被拜访的页面内容应用 import() 配合组件动静导入,不就能达到页面 lazyLoad 的成果了吗?
答案是能够的。然而这样会有一个大问题:被 lazyLoad 的组件中,其内容仅仅是以后组件的代码,并不蕴含援用的其余模块中组件的代码。
起因是 Angular 利用由多个模块组成,每个模块中须要的性能可能来自其余模块,比方 A 模块里要用到 table
组件,而 table
需取自于 ng-zorro-antd/table
模块。打包时 Angular 不像 React 或 Vue 能够把以后组件和用到的其余包一起打包,以 React 为例:在 A 组件引入 table 组件,打包时 table 代码会打包到 A 组件中。而 Angular 中,在 A 组件中应用 table 组件时,并且应用 imprt()
对 A 组件进行动静加载,打包进去的 A 组件并不蕴含 table 的代码, 而是会把 table 代码打包到以后模块中去,如果一个模块中蕴含多个页面,这么多页面用了不少UI组件,那么打包进去的模块必定会很大。
那么就没有别的办法了吗?答案是有的,那就是把每个页面拆成一个 module,每个页面所用到的其余模块或组件由当前页面对应的模块所承当。
上图中 dashboard
作为一个模块,其下有两个页面,别离是 monitor
和 welcome
dashboard.module.ts:
import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';import { RouterModule, Routes } from '@angular/router';const routes: Routes = [ { path: 'welcome', loadChildren: () => import('./welcome/welcome.module').then((m) => m.WelcomeModule), }, { path: 'monitor', loadChildren: () => import('./monitor/monitor.module').then((m) => m.MonitorModule), },];@NgModule({ imports: [CommonModule, RouterModule.forChild(routes)], exports: [RouterModule], declarations: [],})export class DashboardModule {}
在模块中应用路由 loadChildren 来 lazyLoad 两个页面模块,当初再看看 WelcomeModule:
import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';import { WelcomeComponent } from './welcome.component';import { RouterModule, Routes } from '@angular/router';const routes: Routes = [ { path: '', component: WelcomeComponent }];@NgModule({ declarations: [WelcomeComponent], imports: [RouterModule.forChild(routes), CommonModule]})export class WelcomeModule {}
就是这么简略,就把页面级的 lazyLoad 实现了。当须要应用内部组件时,比方 table 组件,只有在 imports 引入即可:
import { NzTableModule } from 'ng-zorro-antd/table';@NgModule({ ... imports: [..., NzTableModule]})export class WelcomeModule {}
题外话:我更喜爱 React 的拆分形式,举个例子:React 中应用 table 组件,table 组件自身代码量比拟大,如果很多页面都应用 table,那么每个页面都会有 table 代码,造成不必要的节约。所以能够配合 import()
把 table
组件单拉进去,打包时 table
作为独自的 js
被浏览器下载并提供给须要的页面应用,所有页面共享这一份 js
即可。但 Angular 做不到,它无奈在模块的 imports
中应用 import()
的模块 。
后续
以上都是对我的项目代码做了比拟正当的拆分,后续会对 Angular 性能上做正当的优化,次要从编译模式、变更检测、ngFor、Worker等角度来论述。另外也会独自写一篇对于 Angular 状态治理的文章
敬请期待