现代化构建的配置技巧
性能优化与现代化构建的核心思路
Vite.js 作为新一代前端构建工具,其核心理念是利用浏览器原生 ESM 特性实现快速开发体验。性能优化需要从开发时和生产环境两个维度考虑:
- 开发时:利用 ESM 按需编译特性
- 生产时:基于 Rollup 的打包优化
开发环境优化配置
依赖预构建策略
Vite 默认会对 node_modules
进行预构建,但可以通过配置精细化控制:
// vite.config.js
export default defineConfig({
optimizeDeps: {
include: ['lodash-es', 'axios'],
exclude: ['vue-demi'],
force: true // 强制重新预构建
}
})
模块热替换(HMR)优化
自定义 HMR 处理逻辑可以提升大型项目更新速度:
if (import.meta.hot) {
import.meta.hot.accept('./module.js', (newModule) => {
console.log('模块更新:', newModule)
// 自定义更新逻辑
})
}
生产环境构建优化
代码分割策略
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: (id) => {
if (id.includes('node_modules')) {
if (id.includes('lodash')) {
return 'lodash'
}
if (id.includes('d3')) {
return 'd3'
}
return 'vendor'
}
}
}
}
}
})
资源压缩配置
import { defineConfig } from 'vite'
import viteCompression from 'vite-plugin-compression'
export default defineConfig({
plugins: [
viteCompression({
algorithm: 'brotliCompress',
ext: '.br'
})
]
})
高级优化技巧
按需加载组件
对于 UI 库的优化示例:
// vite.config.js
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
Components({
resolvers: [
ElementPlusResolver({
importStyle: 'sass'
})
]
})
]
})
WASM 优化处理
export default defineConfig({
optimizeDeps: {
exclude: ['@ffmpeg/ffmpeg', '@ffmpeg/util']
},
plugins: [
wasmPack(['./crate-1', './crate-2'])
]
})
缓存策略优化
文件指纹配置
export default defineConfig({
build: {
rollupOptions: {
output: {
assetFileNames: 'assets/[name]-[hash][extname]',
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name]-[hash].js'
}
}
}
})
持久化缓存配置
export default defineConfig({
cacheDir: './.vite_cache',
build: {
manifest: true
}
})
现代化构建特性应用
使用 Top-Level Await
// 直接使用顶层 await
const data = await fetchData()
export default { data }
Worker 线程优化
// worker.js
self.onmessage = (e) => {
const result = heavyCalculation(e.data)
self.postMessage(result)
}
// 主线程
const worker = new Worker(new URL('./worker.js', import.meta.url))
构建分析工具集成
可视化分析插件
import { visualizer } from 'rollup-plugin-visualizer'
export default defineConfig({
plugins: [
visualizer({
open: true,
gzipSize: true,
brotliSize: true
})
]
})
自定义报告生成
import { defineConfig } from 'vite'
import { execSync } from 'child_process'
export default defineConfig({
plugins: [
{
name: 'generate-report',
closeBundle() {
execSync('npx vite-bundle-analyzer report.html')
}
}
]
})
环境变量与模式优化
智能环境变量处理
// vite.config.js
export default defineConfig({
define: {
__APP_VERSION__: JSON.stringify(process.env.npm_package_version),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
})
多环境配置策略
// vite.config.js
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
define: {
'process.env.API_BASE': JSON.stringify(env.API_BASE)
}
}
})
服务端渲染(SSR)优化
SSR 构建配置
export default defineConfig({
build: {
ssr: true,
rollupOptions: {
input: 'src/entry-server.js'
}
}
})
客户端激活配置
export default defineConfig({
ssr: {
noExternal: ['react-router-dom'],
external: ['aws-sdk']
}
})
图片与静态资源处理
图片压缩策略
import viteImagemin from 'vite-plugin-imagemin'
export default defineConfig({
plugins: [
viteImagemin({
gifsicle: { optimizationLevel: 7 },
optipng: { optimizationLevel: 7 }
})
]
})
SVG 组件化处理
import svgLoader from 'vite-svg-loader'
export default defineConfig({
plugins: [svgLoader()]
})
现代化 JavaScript 支持
浏览器兼容性配置
export default defineConfig({
build: {
target: ['es2020', 'edge88', 'firefox78', 'chrome87', 'safari14']
}
})
Polyfill 按需引入
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
plugins: [
legacy({
targets: ['defaults', 'not IE 11']
})
]
})
构建性能监控
构建耗时分析
export default defineConfig({
plugins: [
{
name: 'build-time',
configResolved(config) {
console.time('Build Time')
},
closeBundle() {
console.timeEnd('Build Time')
}
}
]
})
内存使用监控
export default defineConfig({
plugins: [
{
name: 'memory-usage',
buildStart() {
if (process.env.NODE_ENV === 'production') {
setInterval(() => {
const used = process.memoryUsage().heapUsed / 1024 / 1024
console.log(`Memory Usage: ${Math.round(used * 100) / 100} MB`)
}, 5000)
}
}
}
]
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn