webpack项目打包优化

externals 方案

将体积大而且不需要按需加载的包通过CDN的方式加载, 不参与打包, 例如: vueaxiosvue-router , 通过CDN加载的包不能使用Vue.use()

引入资源

在 index.html 中通过 link 和 script 方法引入所需的 js 和 css

配置 externals

webpack.dev.conf.jswebpack.prod.conf.jsmodule下均添加externals, 这样webpack编译打包时不处理它, 却可以 import 引用到它。

vue-cli3.0 不需要以上此配置。

按需加载

每个包按需加载的方式都不同, 这里以 element-ui 为例, 在main.js主入口文件中给element-ui组件库做按需导入设置,去除没有使用的组件,进一步精简项目的总代码量。
参考: https://element.eleme.cn/#/zh-CN/component/quickstart

安装 babel-plugin-component

1
npm install babel-plugin-component -D

修改 .babelrc

按需引入

完整组件列表和引入方式(完整组件列表以 components.json 为准)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import Vue from "vue"
import {
Pagination,
Dialog,
Autocomplete,
Dropdown,
DropdownMenu,
DropdownItem,
Menu,
Submenu,
MenuItem,
MenuItemGroup,
Input,
InputNumber,
Radio,
// ...
Loading,
MessageBox,
Message,
Notification,
} from "element-ui"

Vue.prototype.$ELEMENT = { size: "small" } // element-ui的全局配置

Vue.use(Pagination)
Vue.use(Dialog)
Vue.use(Autocomplete)
Vue.use(Dropdown)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Menu)
Vue.use(Submenu)
Vue.use(MenuItem)
Vue.use(MenuItemGroup)
Vue.use(Input)
Vue.use(InputNumber)
Vue.use(Radio)
// ...
Vue.use(Loading.directive)

Vue.prototype.$loading = Loading.service
Vue.prototype.$msgbox = MessageBox
Vue.prototype.$alert = MessageBox.alert
Vue.prototype.$confirm = MessageBox.confirm
Vue.prototype.$prompt = MessageBox.prompt
Vue.prototype.$notify = Notification
Vue.prototype.$message = Message