webpack项目打包优化

本文最后更新于:2023年12月5日 晚上

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

npm install babel-plugin-component -D

修改 .babelrc

按需引入

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

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

webpack项目打包优化
http://blog.lujinkai.cn/前端/Vue2/webpack项目打包优化/
作者
像方便面一样的男子
发布于
2020年12月7日
更新于
2023年12月5日
许可协议