关于 vite
面向 JavaScript 和 TypeScript 前端开发者的 Vite 技能,涵盖项目配置、开发流程、资源处理与生产构建。
主要功能
- 01Vite 配置与项目初始化
- 02环境变量与路径别名
- 03热模块替换
- 04资源与 CSS 处理
- 05构建优化与 SSR
- 06插件开发
适用场景
- 01搭建 Vite 前端项目
- 02配置 React、Vue 或 Svelte 项目
- 03调整生产构建分块
- 04设置代理或 SSR
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mindrally/ skills --skill vite安装后在 Claude Code 中输入/vite确认已加载。
详细介绍
Vite 开发
你是 Vite、现代 JavaScript/TypeScript 构建工具和前端开发方面的专家。
核心原则
- 利用原生 ES 模块实现快速开发
- 尽可能使用 Vite 的约定式默认配置
- 只配置需要自定义的内容
- 了解开发与构建之间的差异
- 同时优化开发速度和生产环境性能
项目设置
基本配置
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
open: true,
},
build: {
outDir: 'dist',
sourcemap: true,
},
});
路径别名
import { defineConfig } from 'vite';
import path from 'path';
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@utils': path.resolve(__dirname, './src/utils'),
},
},
});
环境变量
用法
// .env
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My App
// 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;
类型定义
// src/vite-env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string;
readonly VITE_APP_TITLE: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
热模块替换
手动 HMR
// For libraries without HMR support
if (import.meta.hot) {
import.meta.hot.accept('./module.ts', (newModule) => {
// Handle the updated module
console.log('Module updated:', newModule);
});
import.meta.hot.dispose(() => {
// Cleanup before module is replaced
});
}
资源处理
静态资源
// Import as URL
import imageUrl from './image.png';
// <img src={imageUrl} />
// Import as string (raw)
import shaderCode from './shader.glsl?raw';
// Import as worker
import Worker from './worker.ts?worker';
const worker = new Worker();
公共目录
public/
├── favicon.ico # Served at /favicon.ico
├── robots.txt # Served at /robots.txt
└── images/ # Served at /images/
框架集成
React
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
// Enable Fast Refresh
fastRefresh: true,
// Babel plugins
babel: {
plugins: ['@emotion/babel-plugin'],
},
}),
],
});
Vue
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
});
Svelte
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default defineConfig({
plugins: [svelte()],
});
构建优化
代码拆分
// Dynamic imports create separate chunks
const AdminPanel = lazy(() => import('./AdminPanel'));
// Manual chunks
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
utils: ['lodash', 'date-fns'],
},
},
},
},
});
分块大小优化
export default defineConfig({
build: {
chunkSizeWarningLimit: 500,
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return id.split('node_modules/')[1].split('/')[0];
}
},
},
},
},
});
CSS 处理
CSS 模块
// styles.module.css is auto-detected
import styles from './styles.module.css';
// <div className={styles.container}>
PostCSS
// postcss.config.js
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
预处理器
// Automatically handled with package installed
// npm install -D sass
import './styles.scss';
代理配置
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:4000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
'/socket.io': {
target: 'ws://localhost:4000',
ws: true,
},
},
},
});
插件开发
// my-vite-plugin.ts
import type { Plugin } from 'vite';
export function myPlugin(): Plugin {
return {
name: 'my-plugin',
// Hook: modify config
config(config, { mode }) {
return {
define: {
__BUILD_TIME__: JSON.stringify(new Date().toISOString()),
},
};
},
// Hook: transform code
transform(code, id) {
if (id.endsWith('.md')) {
return {
code: `export default ${JSON.stringify(code)}`,
map: null,
};
}
},
// Hook: configure dev server
configureServer(server) {
server.middlewares.use((req, res, next) => {
// Custom middleware
next();
});
},
};
}
使用 Vitest 进行测试
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
},
},
});
SSR 配置
export default defineConfig({
build: {
ssr: true,
rollupOptions: {
input: './src/entry-server.ts',
},
},
ssr: {
external: ['express'],
noExternal: ['my-ui-library'],
},
});
库模式
export default defineConfig({
build: {
lib: {
entry: './src/index.ts',
name: 'MyLib',
fileName: (format) => `my-lib.${format}.js`,
},
rollupOptions: {
external: ['react', 'react-dom'],
output: {
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
},
},
},
});
最佳实践
- 使用
vite preview在本地测试生产构建 - 将支持 ESM 的依赖保留在常规依赖中
- 对 CommonJS 依赖使用
optimizeDeps.include - 启用
build.sourcemap以便调试生产环境 - 使用
server.warmup加快开发服务器启动速度
评论
支持 Markdown