-
Notifications
You must be signed in to change notification settings - Fork 6
Vue-Cli / Ant Design Vue 项目打包体积优化 #151
Copy link
Copy link
Closed
Labels
DeploymentDeploy content to serverDeploy content to server
Description
需求描述
用 Vue-Cli / Ant Design Vue 默认配置打包生成的静态资源文件有 6M 多,体积太大了,就很有必要进行打包优化。
解决过程
查找资料
先用关键字 vue-cli打包体积优化 Google 一下,第一个链接 Vue 打包体积优化方案 讲得就挺全面,提到可以安装 webpack-bundle-analyzer 这个库,来分析打包后各个文件占用了多大的体积。在评论中又有用户说到 webpack-bundle-analyzer 这个库在 Vue-Cli 中已经集成了,如果是用 Vue-Cli 从头创建的项目,只需要执行 npx vue-cli-server build --report,就会自动调用 webpack-bundle-analyzer 这个库来生成打包文件的分析报告。
另外还可针对 Ant Design Vue 的具体情况进行专门的优化,关键字见 ant design vue打包体积优化。
生产环境 JS 库使用 CDN 文件
在某项目中,所用到的配置代码如下:
// vue.config.js
const externals = {
vue: 'Vue',
'vue-router': 'VueRouter',
vuex: 'Vuex',
axios: 'axios'
}
const cdn = {
css: [],
js: [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-router.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/vuex.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js'
]
}
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
chainWebpack: config => {
// 生产环境展示各打包文件体积,以便优化
if (isProd) {
config
.plugin('webpack-bundle-analyzer')
.use(require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin)
}
// 生产环境使用 CDN 中的库
config
.plugin('html')
.tap(args => {
if (isProd) {
args[0].cdn = cdn
}
return args
})
},
configureWebpack: config => {
// 生产环境使用 CDN 中的库
if (isProd) {
return {
externals: externals
}
}
}
}<head>
<!-- 使用CDN的CSS文件 -->
<% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css) { %>
<link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="external nofollow" rel="external nofollow" rel="preload" as="style">
<link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="external nofollow" rel="external nofollow" rel="stylesheet">
<% } %>
<!-- 使用CDN的JS文件 -->
<% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>
<link href="<%= htmlWebpackPlugin.options.cdn.js[i] %>" rel="external nofollow" rel="preload" as="script">
<% } %>
</head>
<body>
<% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>
<script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
<% } %>
</body>Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
DeploymentDeploy content to serverDeploy content to server