本项目已经集成了多种性能优化策略,以提升应用的加载速度和运行性能。
# 开发环境(已优化)
npm run dev
# 生产构建(已优化)
npm run build
# 性能分析
npm run analyze
# 完整性能测试
npm run performance
npm run analyze:install
npm run analyze
这将生成:
bundle-report.html
- 可视化打包分析bundle-stats.json
- 详细统计数据performance-report.md
- 性能报告分析完成后会自动打开浏览器显示可视化报告。
// webpack.config.js 中的性能预算
performance: {
maxAssetSize: 2000000, // 2MB
maxEntrypointSize: 2000000, // 2MB
hints: 'warning'
}
// 使用动态导入
const LazyComponent = () => import('@/components/LazyComponent.vue')
// 路由懒加载
const routes = [
{
path: '/lazy',
component: () => import('@/views/LazyView.vue')
}
]
<template>
<div>
<!-- 使用v-show代替v-if(频繁切换) -->
<div v-show="visible">Content</div>
<!-- 长列表虚拟滚动 -->
<virtual-list :items="items" />
</div>
</template>
<script>
export default {
// 组件缓存
keep-alive: true,
// 异步组件
components: {
AsyncComponent: () => import('./AsyncComponent.vue')
}
}
</script>
<!-- 使用WebP格式 -->
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="description">
</picture>
<!-- 响应式图片 -->
<img
src="image-320.jpg"
srcset="image-320.jpg 320w, image-640.jpg 640w, image-1280.jpg 1280w"
sizes="(max-width: 320px) 320px, (max-width: 640px) 640px, 1280px"
alt="description"
>
# Nginx配置示例
server {
# 启用Gzip
gzip on;
gzip_types text/plain text/css application/json application/javascript;
# 启用Brotli
brotli on;
brotli_types text/plain text/css application/json application/javascript;
# 缓存静态资源
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
项目包含 performance.config.js
配置文件,可以调整各种性能参数:
// performance.config.js
module.exports = {
// 预加载策略
preload: {
critical: ['vue-vendor', 'element-ui', 'main'],
prefetch: true
},
// 代码分割
splitChunks: {
maxInitialRequests: 6,
minSize: 100000,
maxSize: 8000000
},
// 压缩配置
compression: {
gzip: { threshold: 8192 },
brotli: { threshold: 8192, level: 11 }
}
}
# 安装Lighthouse
npm install -g lighthouse
# 运行测试
lighthouse http://localhost:3000 --output html --output-path ./lighthouse-report.html
# 生成分析报告
npm run analyze
# 查看具体文件大小
npm run build -- --profile --json > stats.json
--max-old-space-size=8192
避免内存溢出node_modules/.cache
目录优化项目 | 优化前 | 优化后 | 提升 |
---|---|---|---|
JS文件数量 | 66个 | 33个 | 50% ↓ |
首页加载文件 | 29个 | 16个 | 45% ↓ |
构建速度 | - | 缓存加速 | 30% ↑ |
文件压缩 | 无 | Gzip+Brotli | 70% ↓ |
持续优化,持续改进! 🎯