Angular 打包优化

摘要

本文主要讲了在 angular 项目中使用了 moment、@ng-bootstrap/ng-bootstrap、echarts 后,如何去掉其中没有用到的模块,从而减小体积。同时文中的解决方法也可以延伸到其他类似库。

moment

问题

如果在项目要用到 moment 库,在打包的时候需要注意一件事情,就是它会默认包含 locale(日期时间的国际化)库,在压缩之后会占用 286K 之多,这对于没有用到这部分功能的项目来说是非常多余的,所以应该想办法干掉。

解决

1、对于 ng-cli 的项目:

  • 运行 npm uninstall moment
  • 运行 npm install moment --save-dev
  • .angular-cli.json 文件的 scripts 里加上
    "../node_modules/moment/min/moment.min.js"
  • typings.d.ts 文件的最后加上 declare var moment: any;
  • 将项目中的代码 import * as moment from 'moment'; 全部干掉

备注:如果想应用其中某个库则需要(以 fr 为例)

  • 引入:import "moment/locale/fr";
  • 使用:moment.locale("fr");

2、对于 webpack 的项目:

在 webpack 配置文件的 plugins 里加上

1
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, / /)

或者

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

备注:如果想应用其中某个库则需要(以 de、fr、hu 为例)

在 webpack 配置文件的 plugins 里加上

1
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /de|fr|hu/)
结果对比:(某个 ng-cli 项目)

1、通过 source-map-explorer
优化之前:
image
优化之后:
image

@ng-bootstrap/ng-bootstrap

问题

如果在项目中要用到 @ng-bootstrap/ng-bootstrap 库,要注意一下使用方法,如果按照其官网示例方式引入的话,在打包的时候会把其下所有模块引入进来,不管你用没用到。所以要想办法把没有用到的模块干掉,只引入需要的模块。

解决

以时间组件为例,官网示例:

1
2
3
4
5
6
7
8
9
10
// 根模块
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
declarations: [AppComponent, ...],
imports: [NgbModule.forRoot(), ...],
bootstrap: [AppComponent]
})
export class AppModule {
}
1
2
3
4
5
6
7
8
9
// 其他需要模块
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
declarations: [OtherComponent, ...],
imports: [NgbModule, ...],
})
export class OtherModule {
}

更改为:

1
2
3
4
5
6
7
8
9
10
// 根模块
import {NgbDatepickerModule, NgbTimepickerModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
declarations: [AppComponent, ...],
imports: [NgbDatepickerModule.forRoot(), NgbTimepickerModule.forRoot() ...],
bootstrap: [AppComponent]
})
export class AppModule {
}
1
2
3
4
5
6
7
8
9
// 其他需要模块
import {NgbDatepickerModule, NgbTimepickerModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
declarations: [OtherComponent, ...],
imports: [NgbDatepickerModule, NgbTimepickerModule, ...],
})
export class OtherModule {
}
结果对比:(以只引入 NgbDatepickerModule、NgbTimepickerModule 这两个模块为例)

官网方式引入:
image
单独模块引入:
image

echarts

echarts 支持按需加载,详细的可以看官方教程的在 webpack 中使用 ECharts这部分。

------------- 本文结束 感谢您的阅读 -------------

本文标题:Angular 打包优化

文章作者:水中熊

发布时间:2018年06月19日 - 10:06

最后更新:2018年06月19日 - 11:06

原始链接:https://shuizhongxiong.github.io/ng-optimize.html

许可协议: 知识共享署名-非商业性使用-相同方式共享 3.0 中国大陆许可协议进行许可。 转载请保留原文链接及作者。

🌹坚持原创技术分享,您的支持将鼓励我继续创作!🌹
0%