关于 vite
供开发者搭建和配置 Vite 项目的速查技能,涵盖应用初始化、环境变量、开发工作流和构建优化。
主要功能
- 01React、Vue 和 Svelte 初始化指南
- 02开发服务器与代理配置
- 03环境变量用法
- 04代码拆分与构建优化
- 05故障排查和生产检查清单
适用场景
- 01启动 Vite 应用项目
- 02配置开发代理
- 03管理客户端环境变量
- 04准备生产构建
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill vite安装后在 Claude Code 中输入/vite确认已加载。
详细介绍
Vite - 快速参考
何时使用此技能
- 搭建 React/Vue/Svelte 项目
- 配置开发服务器和代理
- 优化生产构建
深入了解:使用
mcp__documentation__fetch_docs并将技术指定为:vite,以获取全面的文档。
何时不使用此技能
- 基于 Webpack 的项目 - 使用
webpack技能配置 webpack.config.js - Next.js - 自带构建系统(使用 SWC/Turbopack)
- Create React App - 仍在使用 Webpack(可考虑迁移)
- 纯 Rollup - 直接使用 Rollup 构建库
核心模式
设置
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev
基本配置
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
}
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
},
build: {
outDir: 'dist',
sourcemap: true
}
});
环境变量
# .env
VITE_API_URL=http://localhost:8080/api
// Usage
const apiUrl = import.meta.env.VITE_API_URL;
const isProd = import.meta.env.PROD;
// TypeScript types (vite-env.d.ts)
interface ImportMetaEnv {
readonly VITE_API_URL: string;
}
代码拆分
// Dynamic imports
const AdminPanel = lazy(() => import('./AdminPanel'));
// Manual chunks
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
}
}
}
}
});
命令
| 命令 | 用途 |
|---|---|
npm run dev | 开发服务器 HMR |
npm run build | 构建生产版本 |
npm run preview | 预览构建结果 |
应避免的反模式
- 不要忘记为环境变量添加
VITE_前缀 - 不要使用相对路径(请使用别名)
- 不要忽略分块大小警告
反模式
| 反模式 | 不良原因 | 正确做法 |
|---|---|---|
| 环境变量没有 VITE_ 前缀 | 不会暴露给客户端 | 所有客户端变量都需要 VITE_ 前缀 |
| 相对导入 | 难以重构 | 使用路径别名(@/...) |
| 忽略分块大小警告 | 初始包体积过大 | 使用手动分块或延迟加载 |
| 配置未使用 TypeScript | 缺少类型提示 | 使用 'vite' 中的 defineConfig |
| 未区分开发/生产环境 | 两者使用相同配置 | 使用特定环境的 .env 文件 |
| public 文件夹过大 | 构建速度慢 | public/ 中仅放置静态资源 |
快速故障排除
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 环境变量未定义 | 缺少 VITE_ 前缀 | 重命名为 VITE_API_URL |
| HMR 不工作 | 代理配置 | 检查 server.hmr 设置 |
| 动态导入导致构建失败 | 语法错误 | 使用 import(),而非 require() |
| 开发服务器速度慢 | 依赖项过多 | 添加到 optimizeDeps.include |
| 刷新时出现 404(SPA) | 缺少回退 | 添加 server.historyApiFallback |
| 开发环境出现 CORS 错误 | 代理配置错误 | 正确配置 server.proxy |
生产环境就绪
构建优化
// vite.config.ts
import { defineConfig, splitVendorChunkPlugin } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({
plugins: [
react(),
splitVendorChunkPlugin(),
visualizer({ open: true }), // Bundle analysis
],
build: {
target: 'es2020',
minify: 'esbuild',
sourcemap: true,
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
router: ['react-router-dom'],
ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
},
},
},
chunkSizeWarningLimit: 500,
},
// Optimize deps
optimizeDeps: {
include: ['react', 'react-dom'],
exclude: ['@some/heavy-package'],
},
});
安全配置
// vite.config.ts
export default defineConfig({
// Never expose server-only vars
define: {
'process.env.API_SECRET': 'undefined',
},
server: {
// CORS for dev
cors: {
origin: 'http://localhost:3000',
credentials: true,
},
// Proxy to avoid CORS issues
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
secure: false,
},
},
},
// Preview server (for testing prod builds)
preview: {
port: 4173,
strictPort: true,
},
});
// Type-safe env vars
// env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string;
readonly VITE_APP_TITLE: string;
// Add all VITE_ prefixed vars here
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
性能
// vite.config.ts
export default defineConfig({
build: {
// CSS code splitting
cssCodeSplit: true,
// Asset inlining threshold (4kb)
assetsInlineLimit: 4096,
// Terser for smaller bundles (slower build)
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
},
},
},
// Enable compression
plugins: [
react(),
compression({ algorithm: 'gzip' }),
compression({ algorithm: 'brotliCompress', ext: '.br' }),
],
});
// Lazy loading routes
// router.tsx
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));
const routes = [
{
path: '/dashboard',
element: (
<Suspense fallback={<Loading />}>
<Dashboard />
</Suspense>
),
},
];
测试配置
// vite.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['./src/test/setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
exclude: ['node_modules/', 'src/test/'],
},
include: ['src/**/*.{test,spec}.{js,ts,jsx,tsx}'],
},
});
// src/test/setup.ts
import '@testing-library/jest-dom';
import { vi } from 'vitest';
// Mock environment variables
vi.stubEnv('VITE_API_URL', 'http://localhost:8080');
CI/CD 集成
# .github/workflows/build.yml
name: Build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- name: Type check
run: npm run typecheck
- name: Lint
run: npm run lint
- name: Test
run: npm run test:coverage
- name: Build
run: npm run build
- name: Upload coverage
uses: codecov/codecov-action@v4
监控指标
| 指标 | 目标 |
|---|---|
| 包体积(gzip) | < 200KB |
| 初始加载时间 | < 2s |
| 构建时间 | < 60s |
| Lighthouse 性能 | > 90 |
检查清单
- 类型安全的环境变量
- 为大型依赖项手动分块
- 使用 visualizer 分析包体积
- 路由启用延迟加载
- 启用 CSS 代码拆分
- 压缩(gzip/brotli)
- 生产环境移除 console
- 启用 source maps
- 配置带覆盖率的 Vitest
- CI/CD 流水线
延伸阅读
有关高级配置:
mcp__documentation__fetch_docs
- 技术:
vite- Vite 文档
评论
支持 Markdown