跳到主要内容

Vite

Vite 是一个现代化的前端构建工具,它利用浏览器原生 ES 模块导入特性,在开发环境下实现了快速的模块热重载(HMR),并通过 Rollup 在生产环境下进行高效的打包。

1. 基础配置

1.1 安装和创建项目

# 使用 npm
npm create vite@latest my-app -- --template react-ts

# 使用 yarn
yarn create vite my-app --template react-ts

# 使用 pnpm
pnpm create vite my-app --template react-ts

# 支持的模板
# vanilla, vanilla-ts, vue, vue-ts, react, react-ts, preact, preact-ts, lit, lit-ts, svelte, svelte-ts

1.2 配置文件

// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
// 插件
plugins: [react()],

// 开发服务器配置
server: {
port: 3000,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},

// 构建配置
build: {
outDir: 'dist',
assetsDir: 'assets',
sourcemap: true
},

// 解析配置
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
});

2. 开发特性

2.1 热模块替换 (HMR)

// main.ts
if (import.meta.hot) {
import.meta.hot.accept((newModule) => {
// 自定义 HMR 处理逻辑
});
}

// vite.config.ts HMR 配置
export default defineConfig({
server: {
hmr: {
overlay: false, // 禁用错误遮罩
port: 24678 // 自定义 WebSocket 端口
}
}
});

2.2 环境变量

// .env
VITE_API_URL=http://api.example.com

// .env.development
VITE_API_URL=http://localhost:3000

// 使用环境变量
console.log(import.meta.env.VITE_API_URL);

// vite.config.ts
export default defineConfig({
define: {
__APP_VERSION__: JSON.stringify('1.0.0')
}
});

3. 构建优化

3.1 代码分割

// vite.config.ts
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
'vendor': ['react', 'react-dom'],
'utils': ['lodash-es', 'axios']
}
}
}
}
});

// 动态导入
const MyComponent = () => {
const Component = React.lazy(() => import('./Component'));
return (
<Suspense fallback={<div>Loading...</div>}>
<Component />
</Suspense>
);
};

3.2 资源处理

// vite.config.ts
export default defineConfig({
build: {
// 资源内联阈值
assetsInlineLimit: 4096,

// 自定义 Rollup 配置
rollupOptions: {
output: {
assetFileNames: 'assets/[name].[hash].[ext]'
}
}
}
});

// 静态资源导入
import logo from './logo.png';
import styles from './style.module.css';

4. 插件系统

4.1 常用插件

// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import legacy from '@vitejs/plugin-legacy';
import compression from 'vite-plugin-compression';

export default defineConfig({
plugins: [
// React 支持
react(),

// 旧浏览器支持
legacy({
targets: ['defaults', 'not IE 11']
}),

// Gzip 压缩
compression({
algorithm: 'gzip',
ext: '.gz'
})
]
});

4.2 自定义插件

// myPlugin.ts
import type { Plugin } from 'vite';

export default function myPlugin(): Plugin {
return {
name: 'my-plugin',

// 配置
config(config) {
return {
// 修改配置
};
},

// 转换
transform(code, id) {
if (id.endsWith('.vue')) {
return {
code: transformedCode,
map: sourceMap
};
}
},

// 构建钩子
buildStart() {
// 构建开始
},
buildEnd() {
// 构建结束
}
};
}

5. 性能优化

5.1 预构建优化

// vite.config.ts
export default defineConfig({
optimizeDeps: {
// 强制预构建的依赖
include: ['lodash-es', '@apollo/client'],

// 排除预构建的依赖
exclude: ['your-local-package'],

// 自定义 esbuild 配置
esbuildOptions: {
target: 'es2020'
}
}
});

5.2 构建优化

// vite.config.ts
export default defineConfig({
build: {
// 启用/禁用 brotli 压缩大小报告
brotliSize: false,

// chunk 大小警告的限制
chunkSizeWarningLimit: 500,

// 最小化混淆
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
},

// CSS 代码分割
cssCodeSplit: true,

// 设置为 false 可以禁用自动拆分 vendor chunk
splitVendorChunkPlugin: false
}
});

6. 部署配置

6.1 基础路径配置

// vite.config.ts
export default defineConfig({
base: '/my-app/',

build: {
// 生成静态资源的存放目录
assetsDir: 'static',

// 小于此阈值的导入或引用资源将内联为 base64 编码
assetsInlineLimit: 4096,

// 启用/禁用 CSS 代码拆分
cssCodeSplit: true,

// 构建后是否生成 source map 文件
sourcemap: false
}
});

6.2 SSR 配置

// vite.config.ts
export default defineConfig({
ssr: {
// SSR 特定配置
external: ['react', 'react-dom'],
noExternal: ['some-package'],

// 强制预构建的依赖项
optimizeDeps: {
include: ['lodash-es']
}
}
});

// server.js
import { createServer } from 'vite';

const vite = await createServer({
server: { middlewareMode: true },
appType: 'custom'
});

app.use(vite.middlewares);

7. 调试与测试

7.1 调试配置

// vite.config.ts
export default defineConfig({
build: {
// 生产环境启用 source map
sourcemap: true
},

server: {
// 控制台输出更多信息
cors: true,
hmr: {
overlay: true
}
}
});

7.2 测试集成

// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
test: {
// Vitest 配置
globals: true,
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
coverage: {
reporter: ['text', 'json', 'html']
}
}
});

参考资源