关于 vite
介绍将 Vite 7.x 用作 Web 构建工具和开发服务器的技能,涵盖项目设置、环境配置、生产优化及本地构建预览。
主要功能
- 01开发服务器与 HMR 设置
- 02TypeScript 和 React 配置
- 03环境变量指导
- 04代码拆分与压缩
- 05生产构建预览
适用场景
- 01使用 Vite 初始化 Web 项目
- 02配置环境变量
- 03优化生产构建包
- 04在本地预览生产构建
MCP 相关
该技能建议通过 Context7 MCP 使用 `resolve-library-id` 和 `query-docs` 查阅 Vite API 与配置文档。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ dralgorhythm/ claude-agentic-framework --skill vite安装后在 Claude Code 中输入/vite确认已加载。
详细介绍
Vite
**平台:**仅限 Web。移动端演示使用 Expo 和 Metro bundler。请参阅 expo-sdk skill。
使用 Context7 MCP(
resolve-library-id后接query-docs)获取完整 API 参考、插件生态系统和高级配置选项。
概述
用于 Vite 7.x 的构建工具和开发服务器。提供即时启动服务器、快速 HMR、优化的生产构建和一流的 TypeScript 支持。
安装:pnpm add -D vite
工作流
初始设置:
- 创建带有 TypeScript 类型的
vite.config.ts - 安装 React 插件:
pnpm add -D @vitejs/plugin-react - 配置路径别名,让导入更简洁
- 使用
.env文件设置环境变量 - 测试开发服务器:
pnpm vite
生产环境优化:
- 配置代码分割和代码块优化
- 启用构建压缩(gzip/brotli)
- 运行生产构建:
pnpm vite build - 在本地预览构建结果:
pnpm vite preview
基本配置
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'node:path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@hooks': path.resolve(__dirname, './src/hooks'),
'@utils': path.resolve(__dirname, './src/utils'),
}
},
server: {
port: 5173,
strictPort: true,
open: true,
hmr: { overlay: true },
proxy: {
'/api': { target: 'http://localhost:3000', changeOrigin: true }
}
},
build: {
outDir: 'dist',
sourcemap: true,
minify: 'esbuild',
}
});
更新 tsconfig.json 中的路径,使其与别名匹配:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@components/*": ["./src/components/*"]
}
}
}
使用 SWC 的 React(速度更快的替代方案):pnpm add -D @vitejs/plugin-react-swc,从 @vitejs/plugin-react-swc 导入。
默认启用 Fast Refresh,无需配置。
环境变量
# .env - Base config (committed)
VITE_APP_NAME=MyApp
VITE_API_VERSION=v1
# .env.local - Local overrides (gitignored — put secrets here)
VITE_API_URL=http://localhost:3000
# .env.development / .env.production - mode-specific defaults
**重要:**所有环境变量都必须以 VITE_ 开头,才能暴露给客户端代码。
// Access in code
const apiUrl = import.meta.env.VITE_API_URL;
const isDev = import.meta.env.DEV;
const isProd = import.meta.env.PROD;
const mode = import.meta.env.MODE; // 'development' | 'production'
// Type-safe env vars — add to vite-env.d.ts or src/env.d.ts
interface ImportMetaEnv {
readonly VITE_APP_NAME: string;
readonly VITE_API_URL: string;
}
// Runtime validation
if (!import.meta.env.VITE_API_URL) {
throw new Error('VITE_API_URL is required');
}
使用 loadEnv 动态配置:
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
return {
server: { port: Number(env.PORT) || 5173 }
};
});
构建优化
代码分割
export default defineConfig({
build: {
chunkSizeWarningLimit: 500, // KB
rollupOptions: {
output: {
manualChunks: {
'react-vendor': ['react', 'react-dom'],
'router-vendor': ['react-router-dom'],
'animation-vendor': ['framer-motion'],
},
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash][extname]',
}
}
}
});
基于函数的高级代码块拆分——需要按视图拆分时使用:
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('framer-motion')) return 'vendor-animation';
if (id.includes('react')) return 'vendor-react';
return 'vendor';
}
}
压缩
import { compression } from 'vite-plugin-compression2';
// pnpm add -D vite-plugin-compression2
plugins: [
compression({ algorithm: 'gzip', include: /\.(js|css|html|svg)$/ }),
compression({ algorithm: 'brotliCompress', include: /\.(js|css|html|svg)$/ }),
]
仅在生产环境进行压缩:
minify: isDev ? false : 'terser',
terserOptions: { compress: { drop_console: true, drop_debugger: true } }
CSS 和资源
PostCSS / Tailwind:将 css.postcss 指向你的 postcss.config.js。对于大型应用,启用 cssCodeSplit: true(默认值)。
资源处理:
// src/assets — processed by Vite (hashed, optimized)
import logo from '@/assets/logo.svg';
// /public — served as-is, NOT processed
<img src="/images/logo.svg" />
// ❌ Never import from public directory
内联限制:默认将小于 4 KB 的资源以内联 base64 形式处理(assetsInlineLimit: 4096)。
用于子目录托管的基础路径:base: '/my-app/'
Vite 7 注意事项
- Rolldown——基于 Rust 的新型打包器(可选,可加快构建)
- 改进了 TypeScript 支持和 tree-shaking
- 默认配置适用于大多数项目;高级打包器选项很少需要用到
最佳实践
- 使用路径别名,避免
../../../导入混乱 - 为客户端环境变量添加
VITE_前缀,使其自动暴露 - 将大型第三方依赖拆分到单独的代码块,以便更好地利用缓存
- 使用
.env.local存储机密信息,切勿提交到 git - 配置代理处理 API 调用,避免开发时出现 CORS 问题
- 部署前预览构建结果:
pnpm vite build && pnpm vite preview - 使用 esbuild 加快构建,使用 terser 缩小输出体积
- 设置
strictPort: true,避免端口冲突被静默忽略
反模式
- ❌ 忘记为环境变量添加
VITE_前缀 - ❌ 从
/public目录导入,而不是从src/assets导入 - ❌ 提交包含 API 密钥的
.env.local - ❌ 未配置路径别名(导致导入混乱)
- ❌ 在开发环境使用 terser(造成不必要的速度下降)
- ❌ 未设置
strictPort(端口冲突被静默忽略) - ❌ 忽略代码块大小警告(影响加载时间)
- ❌ 使用别名时未设置
tsconfig.json中的路径 - ❌ 将 localhost URL 硬编码(应使用环境变量)
- ❌ 将所有第三方依赖放在单个代码块中(无法利用缓存)
反馈循环
构建分析:
pnpm vite build
# Output shows chunk sizes:
# dist/js/vendor-react-abc123.js 142.34 kB
# dist/js/index-def456.js 87.21 kB
预览测试:
pnpm vite build && pnpm vite preview
# Verify: all routes work, assets load, no console errors
HMR 速度:大多数更新应在 50ms 内完成。检查 Chrome DevTools → Network → 按 “vite” 筛选。