Vite Build Tool
Dev server, HMR, plugins, env vars, build optimization, library mode.
vitebuildfrontendtooling
# Vite
## Create project
```bash
npm create vite@latest my-app -- --template react-ts
npm create vite@latest my-app -- --template vue-ts
```
## vite.config.ts
```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:8000', changeOrigin: true },
},
},
build: {
outDir: 'dist',
sourcemap: true,
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
utils: ['lodash-es', 'date-fns'],
},
},
},
},
})
```
## Env variables
```bash
# .env.local
VITE_API_URL=https://api.example.com
VITE_APP_NAME=MyApp
```
```ts
// Access (VITE_ prefix required for client exposure)
const url = import.meta.env.VITE_API_URL
const isProd = import.meta.env.PROD
// Type-safe:
/// <reference types="vite/client" />
interface ImportMetaEnv { readonly VITE_API_URL: string }
```
## Dynamic imports (code splitting)
```ts
const module = await import('./heavyLib')
const LazyPage = lazy(() => import('./pages/Dashboard'))
```
## Library mode
```ts
build: {
lib: {
entry: 'src/index.ts',
name: 'MyLib',
formats: ['es', 'cjs'],
fileName: (fmt) => `my-lib.${fmt}.js`,
},
rollupOptions: { external: ['react'], output: { globals: { react: 'React' } } },
}
```
## Useful plugins
- `@vitejs/plugin-react` -- React fast refresh
- `@vitejs/plugin-vue` -- Vue SFC
- `vite-plugin-pwa` -- PWA + service worker
- `vite-tsconfig-paths` -- TS path aliases
- `unplugin-auto-import` -- auto-import Vue/React APIs
- `vite-bundle-visualizer` -- bundle size analysis
## HMR API
```ts
if (import.meta.hot) {
import.meta.hot.accept('./module', (newModule) => {
// handle update
})
import.meta.hot.dispose(() => { /* cleanup */ })
}
```API: /api/skills/vite-build