Vite build optimization practice in the Vue3 project
Preface
In modern front-end development, the performance of build tools directly impacts development efficiency and user experience. As a next-generation build tool, Vite has attracted widespread attention for its extremely fast development experience and powerful construction capabilities. As a backend, share hands-on experience using Vite for build optimization in Vue3 projects.
Vite configuration overview
Infrastructure configuration structure
typescript
export default defineConfig({
plugins: [...], // plugin configuration
resolve: {...}, // path parsing
server: {...}, // Dev server
build: {...}, // build configuration
})
Development environment optimization
1. Develop server configurations
typescript
server: {
host: "127.0.0.1",
port: 3000,
proxy: {
"/api": {
target: "http://127.0.0.1:8000",
changeOrigin: true,
ws: true,
},
"/uploads": {
target: "http://127.0.0.1:8000",
changeOrigin: true,
}
}
}
Key Points for Optimization:
- Proxy Configuration: Unify API requests to avoid cross-domain issues
- WebSocket Support: ws: true supports real-time communication
- changeOrigin: Ensures the correctness of the proxy request
2. Path alias optimization
typescript
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
Advantage:
- Simplified import path
- Improved code readability
- Easy to refactor and maintain
Production build optimization
1. Code compression configuration
typescript
build: {
minify: 'terser',
terserOptions: {
compress: {
drop_console: true, // Remove console
drop_debugger: true, // Remove the debugger
pure_funcs: ['console.log'], // Remove a specific function
unused: true, // Remove unused code
}
}
}
Performance Enhancements:
- Reduces bag volume by 30-50%
- Improved runtime performance
- Clean up the debug code
2. Intelligent code segmentation
typescript
rollupOptions: {
output: {
manualChunks: {
'arco': ['@arco-design/web-vue'],
'editor': ['md-editor-v3', 'marked'],
'charts': ['echarts'],
'utils': ['axios', 'dayjs', 'dompurify'],
'vue-vendor': ['vue', 'vue-router', 'pinia'],
}
}
}
Subcontracting Strategies:
- UI component library packaged separately: Reduces the size of the main package
- Tool Library Merge: Centralized management of related functions
- Vue Ecological Separation: Core framework independent caching
- Business module on-demand: Improve loading efficiency
3. Resource file optimization
typescript
assetFileNames: (assetInfo) => {
const name = assetInfo.names?. [0] || assetInfo.name;
if (name?. endsWith('.css')) {
return 'css/[name]-[hash][extname]';
}
return 'assets/[name]-[hash][extname]';
}
File Organization Benefits:
- Clear directory structure
- Version control friendly
- CDN caching optimization
Plugin ecological application
1. Compression plugins
typescript
import viteCompression from 'vite-plugin-compression';
plugins: [
vue(),
viteCompression(),
]
Compression Effect:
- Gzip compression reduces volume by 70%
- Improve transmission efficiency
- Reduced server bandwidth consumption
2. Vue plugin optimization
typescript
plugins: [
vue({
template: {
compilerOptions: {
Production environment removes annotations
comments: false
}
}
})
]
Performance Monitoring and Analysis
1. Build volume warning
typescript
build: {
chunkSizeWarningLimit: 1000, // 1MB warning threshold
}
2. Build analytics
Use rollup-plugin-visualizer to analyze package volume:
bash
npm run build -- --analyze
Dimension of Analysis:
- Volume ratio of modules
- Dependency graph
- Duplicate code detection
Environment Variable Management
1. Multi-environment configuration
typescript
envDir: './', // environment variable file directory
File Structure:
- '.env.development' - development environment
- '.env.production' - Production environment
- '.env.local' - Local override
2. Type-safe environment variables
typescript
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
readonly VITE_SERVER_URL: string
}
Development Experience Optimization
1. Hot-update optimization
- Vue component hot replacement
- Real-time updates on styles
- State holding mechanism
2. Error message enhancement
- TypeScript type checking
- ESLint code specification
- Build mispositioning
Deploy optimization strategies
1. Static resource processing
typescript
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name]-[hash].js',
Caching Strategy:
- File name hashing
- Long-term caching support
- Version updates automatically expire
2. CDN integration
- CDN acceleration for static resources
- Third-party library CDN introduction
- Localized content distribution
Performance test results
Build performance comparison
- Development Startup Time: Reduced from 5s to 1.2s
- Hot update speed: Completed in an average of 200ms
- Production build time: 40% optimization
Package volume optimization
- Main Bag Volume: 45% reduction
- Load above the fold: 60% increase
- Cache Hit Rate: 80% increase
Best Practices Summary
1. Development phase
- Configure proxies wisely
- Enable hot updates
- Optimized path parsing
2. Build phase
- Smart code segmentation
- Resource compression optimization
- Remove debug code
3. Deployment phase
- Static resource caching
- CDN-accelerated provisioning
- Performance monitoring deployment
FAQ resolution
1. Build memory overflow
bash
NODE_OPTIONS="--max-old-space-size=4096" npm run build
2. Dependency pre-built issues
typescript
optimizeDeps: {
include: ['vue', 'vue-router'],
exclude: ['some-large-dep']
}
3. Style processing optimization
typescript
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss"; `
}
}
}
Future optimization direction
1. Build a cache
- Persist build caches
- Incremental build support
- Distributed Build
2. Modular federation
- Micro-front-end architecture
- Runtime module sharing
- Ability to deploy independently
3. New feature applications
- Vite 5.0 New Features
- Rollup optimizations
- Browser-native modules
Summary
Vite's build optimization is a continuous improvement process. Through reasonable configuration and optimization strategies, we can significantly improve development efficiency and user experience. The key is:
- Development Experience First: Quick hot updates and error prompts
- Production Performance Optimization: Intelligent subcontracting and resource compression
- Continuous Monitoring for Improvement: Regularly analyze and optimize build results
As the scale of the project grows, the importance of build optimization becomes more and more prominent. Mastering these optimization techniques can lay a solid foundation for the long-term development of the project.
*Construction optimization is an important part of front-end engineering, which deserves our continued attention and practice. *