[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"article-18":3},{"id":4,"title":5,"title_en":6,"abstract":7,"abstract_en":8,"content":9,"content_en":10,"category":11,"banner_id":12,"banner_path":13,"tags":14,"is_recommend":16,"prev_article":17,"next_article":21,"created_at":25},18,"Vue3项目中的Vite构建优化实践","Vite build optimization practices in Vue3 projects","在现代前端开发中，构建工具的性能直接影响开发效率和用户体验。Vite作为新一代构建工具，以其极速的开发体验和强大的构建能力受到广泛关注。作为一个后端，分享在Vue3项目中使用Vite进行构建优化的实践经验","In modern front-end development, the performance of build tools directly affects development efficiency and user experience. As a new generation of construction tools, Vite has attracted widespread attention for its rapid development experience and powerful construction capabilities. As a backend, share practical experience in using Vite for build optimization in Vue3 projects","# Vue3项目中的Vite构建优化实践\n\n## 前言\n\n> 在现代前端开发中，构建工具的性能直接影响开发效率和用户体验。Vite作为新一代构建工具，以其极速的开发体验和强大的构建能力受到广泛关注。作为一个后端，分享在Vue3项目中使用Vite进行构建优化的实践经验。\n> \n\n## Vite配置概览\n\n### 基础配置结构\n```typescript\nexport default defineConfig({\n    plugins: [...],      \u002F\u002F 插件配置\n    resolve: {...},      \u002F\u002F 路径解析\n    server: {...},       \u002F\u002F 开发服务器\n    build: {...},        \u002F\u002F 构建配置\n})\n```\n\n## 开发环境优化\n\n### 1. 开发服务器配置\n```typescript\nserver: {\n    host: \"127.0.0.1\",\n    port: 3000,\n    proxy: {\n        \"\u002Fapi\": {\n            target: \"http:\u002F\u002F127.0.0.1:8000\",\n            changeOrigin: true,\n            ws: true,\n        },\n        \"\u002Fuploads\": {\n            target: \"http:\u002F\u002F127.0.0.1:8000\",\n            changeOrigin: true,\n        }\n    }\n}\n```\n\n**优化要点：**\n- **代理配置**：统一API请求，避免跨域问题\n- **WebSocket支持**：ws: true 支持实时通信\n- **changeOrigin**：确保代理请求的正确性\n\n### 2. 路径别名优化\n```typescript\nresolve: {\n    alias: {\n        '@': fileURLToPath(new URL('.\u002Fsrc', import.meta.url))\n    }\n}\n```\n\n**优势：**\n- 简化导入路径\n- 提升代码可读性\n- 便于重构和维护\n\n## 生产构建优化\n\n### 1. 代码压缩配置\n```typescript\nbuild: {\n    minify: 'terser',\n    terserOptions: {\n        compress: {\n            drop_console: true,      \u002F\u002F 移除console\n            drop_debugger: true,     \u002F\u002F 移除debugger\n            pure_funcs: ['console.log'], \u002F\u002F 移除特定函数\n            unused: true,            \u002F\u002F 移除未使用代码\n        }\n    }\n}\n```\n\n**性能提升：**\n- 减少包体积30-50%\n- 提升运行时性能\n- 清理调试代码\n\n### 2. 智能代码分割\n```typescript\nrollupOptions: {\n    output: {\n        manualChunks: {\n            'arco': ['@arco-design\u002Fweb-vue'],\n            'editor': ['md-editor-v3', 'marked'],\n            'charts': ['echarts'],\n            'utils': ['axios', 'dayjs', 'dompurify'],\n            'vue-vendor': ['vue', 'vue-router', 'pinia'],\n        }\n    }\n}\n```\n\n**分包策略：**\n- **UI组件库单独打包**：减少主包体积\n- **工具库合并**：相关功能集中管理\n- **Vue生态分离**：核心框架独立缓存\n- **业务模块按需**：提升加载效率\n\n### 3. 资源文件优化\n```typescript\nassetFileNames: (assetInfo) => {\n    const name = assetInfo.names?.[0] || assetInfo.name;\n    if (name?.endsWith('.css')) {\n        return 'css\u002F[name]-[hash][extname]';\n    }\n    return 'assets\u002F[name]-[hash][extname]';\n}\n```\n\n**文件组织优势：**\n- 清晰的目录结构\n- 版本控制友好\n- CDN缓存优化\n\n## 插件生态应用\n\n### 1. 压缩插件\n```typescript\nimport viteCompression from 'vite-plugin-compression';\n\nplugins: [\n    vue(),\n    viteCompression(),\n]\n```\n\n**压缩效果：**\n- Gzip压缩减少70%体积\n- 提升传输效率\n- 减少服务器带宽消耗\n\n### 2. Vue插件优化\n```typescript\nplugins: [\n    vue({\n        template: {\n            compilerOptions: {\n                \u002F\u002F 生产环境移除注释\n                comments: false\n            }\n        }\n    })\n]\n```\n\n## 性能监控与分析\n\n### 1. 构建体积警告\n```typescript\nbuild: {\n    chunkSizeWarningLimit: 1000, \u002F\u002F 1MB警告阈值\n}\n```\n\n### 2. 构建分析\n使用rollup-plugin-visualizer分析包体积：\n```bash\nnpm run build -- --analyze\n```\n\n**分析维度：**\n- 各模块体积占比\n- 依赖关系图谱\n- 重复代码检测\n\n## 环境变量管理\n\n### 1. 多环境配置\n```typescript\nenvDir: '.\u002F',  \u002F\u002F 环境变量文件目录\n```\n\n**文件结构：**\n- `.env.development` - 开发环境\n- `.env.production` - 生产环境\n- `.env.local` - 本地覆盖\n\n### 2. 类型安全的环境变量\n```typescript\ninterface ImportMetaEnv {\n    readonly VITE_API_BASE_URL: string\n    readonly VITE_SERVER_URL: string\n}\n```\n\n## 开发体验优化\n\n### 1. 热更新优化\n- Vue组件热替换\n- 样式实时更新\n- 状态保持机制\n\n### 2. 错误提示增强\n- TypeScript类型检查\n- ESLint代码规范\n- 构建错误定位\n\n## 部署优化策略\n\n### 1. 静态资源处理\n```typescript\nchunkFileNames: 'js\u002F[name]-[hash].js',\nentryFileNames: 'js\u002F[name]-[hash].js',\n```\n\n**缓存策略：**\n- 文件名哈希化\n- 长期缓存支持\n- 版本更新自动失效\n\n### 2. CDN集成\n- 静态资源CDN加速\n- 第三方库CDN引入\n- 地域化内容分发\n\n## 性能测试结果\n\n### 构建性能对比\n- **开发启动时间**：从5s降至1.2s\n- **热更新速度**：平均200ms内完成\n- **生产构建时间**：优化40%\n\n### 包体积优化\n- **主包体积**：减少45%\n- **首屏加载**：提升60%\n- **缓存命中率**：提升80%\n\n## 最佳实践总结\n\n### 1. 开发阶段\n- 合理配置代理\n- 启用热更新\n- 优化路径解析\n\n### 2. 构建阶段\n- 智能代码分割\n- 资源压缩优化\n- 移除调试代码\n\n### 3. 部署阶段\n- 静态资源缓存\n- CDN加速配置\n- 性能监控部署\n\n## 常见问题解决\n\n### 1. 构建内存溢出\n```bash\nNODE_OPTIONS=\"--max-old-space-size=4096\" npm run build\n```\n\n### 2. 依赖预构建问题\n```typescript\noptimizeDeps: {\n    include: ['vue', 'vue-router'],\n    exclude: ['some-large-dep']\n}\n```\n\n### 3. 样式处理优化\n```typescript\ncss: {\n    preprocessorOptions: {\n        scss: {\n            additionalData: `@import \"@\u002Fstyles\u002Fvariables.scss\";`\n        }\n    }\n}\n```\n\n## 未来优化方向\n\n### 1. 构建缓存\n- 持久化构建缓存\n- 增量构建支持\n- 分布式构建\n\n### 2. 模块联邦\n- 微前端架构\n- 运行时模块共享\n- 独立部署能力\n\n### 3. 新特性应用\n- Vite 5.0新特性\n- Rollup最新优化\n- 浏览器原生模块\n\n## 总结\n\nVite的构建优化是一个持续改进的过程。通过合理的配置和优化策略，我们可以显著提升开发效率和用户体验。关键在于：\n\n- **开发体验优先**：快速的热更新和错误提示\n- **生产性能优化**：智能分包和资源压缩\n- **持续监控改进**：定期分析和优化构建结果\n\n随着项目规模的增长，构建优化的重要性会越来越突出。掌握这些优化技巧，能够为项目的长期发展奠定坚实基础。\n\n---\n\n*构建优化是前端工程化的重要环节，值得我们持续关注和实践。*","# Vite build optimization practice in the Vue3 project\n\n## Preface\n\n> 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.\n> \n\n## Vite configuration overview\n\n### Infrastructure configuration structure\n```typescript\nexport default defineConfig({\n    plugins: [...], \u002F\u002F plugin configuration\n    resolve: {...}, \u002F\u002F path parsing\n    server: {...}, \u002F\u002F Dev server\n    build: {...}, \u002F\u002F build configuration\n})\n```\n\n## Development environment optimization\n\n### 1. Develop server configurations\n```typescript\nserver: {\n    host: \"127.0.0.1\",\n    port: 3000,\n    proxy: {\n        \"\u002Fapi\": {\n            target: \"http:\u002F\u002F127.0.0.1:8000\",\n            changeOrigin: true,\n            ws: true,\n        },\n        \"\u002Fuploads\": {\n            target: \"http:\u002F\u002F127.0.0.1:8000\",\n            changeOrigin: true,\n        }\n    }\n}\n```\n\n**Key Points for Optimization:**\n- **Proxy Configuration**: Unify API requests to avoid cross-domain issues\n- WebSocket Support: ws: true supports real-time communication\n- **changeOrigin**: Ensures the correctness of the proxy request\n\n### 2. Path alias optimization\n```typescript\nresolve: {\n    alias: {\n        '@': fileURLToPath(new URL('.\u002Fsrc', import.meta.url))\n    }\n}\n```\n\n**Advantage:**\n- Simplified import path\n- Improved code readability\n- Easy to refactor and maintain\n\n## Production build optimization\n\n### 1. Code compression configuration\n```typescript\nbuild: {\n    minify: 'terser',\n    terserOptions: {\n        compress: {\n            drop_console: true, \u002F\u002F Remove console\n            drop_debugger: true, \u002F\u002F Remove the debugger\n            pure_funcs: ['console.log'], \u002F\u002F Remove a specific function\n            unused: true, \u002F\u002F Remove unused code\n        }\n    }\n}\n```\n\n**Performance Enhancements:**\n- Reduces bag volume by 30-50%\n- Improved runtime performance\n- Clean up the debug code\n\n### 2. Intelligent code segmentation\n```typescript\nrollupOptions: {\n    output: {\n        manualChunks: {\n            'arco': ['@arco-design\u002Fweb-vue'],\n            'editor': ['md-editor-v3', 'marked'],\n            'charts': ['echarts'],\n            'utils': ['axios', 'dayjs', 'dompurify'],\n            'vue-vendor': ['vue', 'vue-router', 'pinia'],\n        }\n    }\n}\n```\n\n**Subcontracting Strategies:**\n- **UI component library packaged separately**: Reduces the size of the main package\n- **Tool Library Merge**: Centralized management of related functions\n- **Vue Ecological Separation**: Core framework independent caching\n- **Business module on-demand**: Improve loading efficiency\n\n### 3. Resource file optimization\n```typescript\nassetFileNames: (assetInfo) => {\n    const name = assetInfo.names?. [0] || assetInfo.name;\n    if (name?. endsWith('.css')) {\n        return 'css\u002F[name]-[hash][extname]';\n    }\n    return 'assets\u002F[name]-[hash][extname]';\n}\n```\n\n**File Organization Benefits:**\n- Clear directory structure\n- Version control friendly\n- CDN caching optimization\n\n## Plugin ecological application\n\n### 1. Compression plugins\n```typescript\nimport viteCompression from 'vite-plugin-compression';\n\nplugins: [\n    vue(),\n    viteCompression(),\n]\n```\n\n**Compression Effect:**\n- Gzip compression reduces volume by 70%\n- Improve transmission efficiency\n- Reduced server bandwidth consumption\n\n### 2. Vue plugin optimization\n```typescript\nplugins: [\n    vue({\n        template: {\n            compilerOptions: {\n                Production environment removes annotations\n                comments: false\n            }\n        }\n    })\n]\n```\n\n## Performance Monitoring and Analysis\n\n### 1. Build volume warning\n```typescript\nbuild: {\n    chunkSizeWarningLimit: 1000, \u002F\u002F 1MB warning threshold\n}\n```\n\n### 2. Build analytics\nUse rollup-plugin-visualizer to analyze package volume:\n```bash\nnpm run build -- --analyze\n```\n\n**Dimension of Analysis:**\n- Volume ratio of modules\n- Dependency graph\n- Duplicate code detection\n\n## Environment Variable Management\n\n### 1. Multi-environment configuration\n```typescript\nenvDir: '.\u002F', \u002F\u002F environment variable file directory\n```\n\n**File Structure:**\n- '.env.development' - development environment\n- '.env.production' - Production environment\n- '.env.local' - Local override\n\n### 2. Type-safe environment variables\n```typescript\ninterface ImportMetaEnv {\n    readonly VITE_API_BASE_URL: string\n    readonly VITE_SERVER_URL: string\n}\n```\n\n## Development Experience Optimization\n\n### 1. Hot-update optimization\n- Vue component hot replacement\n- Real-time updates on styles\n- State holding mechanism\n\n### 2. Error message enhancement\n- TypeScript type checking\n- ESLint code specification\n- Build mispositioning\n\n## Deploy optimization strategies\n\n### 1. Static resource processing\n```typescript\nchunkFileNames: 'js\u002F[name]-[hash].js',\nentryFileNames: 'js\u002F[name]-[hash].js',\n```\n\n**Caching Strategy:**\n- File name hashing\n- Long-term caching support\n- Version updates automatically expire\n\n### 2. CDN integration\n- CDN acceleration for static resources\n- Third-party library CDN introduction\n- Localized content distribution\n\n## Performance test results\n\n### Build performance comparison\n- **Development Startup Time**: Reduced from 5s to 1.2s\n- **Hot update speed**: Completed in an average of 200ms\n- **Production build time**: 40% optimization\n\n### Package volume optimization\n- **Main Bag Volume**: 45% reduction\n- **Load above the fold**: 60% increase\n- **Cache Hit Rate**: 80% increase\n\n## Best Practices Summary\n\n### 1. Development phase\n- Configure proxies wisely\n- Enable hot updates\n- Optimized path parsing\n\n### 2. Build phase\n- Smart code segmentation\n- Resource compression optimization\n- Remove debug code\n\n### 3. Deployment phase\n- Static resource caching\n- CDN-accelerated provisioning\n- Performance monitoring deployment\n\n## FAQ resolution\n\n### 1. Build memory overflow\n```bash\nNODE_OPTIONS=\"--max-old-space-size=4096\" npm run build\n```\n\n### 2. Dependency pre-built issues\n```typescript\noptimizeDeps: {\n    include: ['vue', 'vue-router'],\n    exclude: ['some-large-dep']\n}\n```\n\n### 3. Style processing optimization\n```typescript\ncss: {\n    preprocessorOptions: {\n        scss: {\n            additionalData: `@import \"@\u002Fstyles\u002Fvariables.scss\"; `\n        }\n    }\n}\n```\n\n## Future optimization direction\n\n### 1. Build a cache\n- Persist build caches\n- Incremental build support\n- Distributed Build\n\n### 2. Modular federation\n- Micro-front-end architecture\n- Runtime module sharing\n- Ability to deploy independently\n\n### 3. New feature applications\n- Vite 5.0 New Features\n- Rollup optimizations\n- Browser-native modules\n\n## Summary\n\nVite'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:\n\n- **Development Experience First**: Quick hot updates and error prompts\n- **Production Performance Optimization**: Intelligent subcontracting and resource compression\n- **Continuous Monitoring for Improvement**: Regularly analyze and optimize build results\n\nAs 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.\n\n---\n\n*Construction optimization is an important part of front-end engineering, which deserves our continued attention and practice. *","vue",0,"https:\u002F\u002Fblog4-1316398321.cos.ap-nanjing.myqcloud.com\u002Fblog5\u002F20250730153704__【哲风壁纸】天体景观-宇宙奇观.png",[15],"Vue",false,{"id":18,"title":19,"title_en":20},17,"Go + Elasticsearch 实现智能搜索功能","Go + Elasticsearch enables intelligent search",{"id":22,"title":23,"title_en":24},19,"Vue3中基于mitt的类型安全事件总线实现","Implementation of type-safe event bus based on mitt in Vue3","2025-08-13T18:30:12+08:00"]