Vite — Build Tool Nhanh Cho Web Hiện Đại
Vite là build tool thế hệ mới, dùng ES modules cho dev nhanh, Rollup cho build production. Plugin ecosystem, HMR tức thì, TypeScript native.
Vite là build tool cho web hiện đại. Dev server dùng native ES modules — khởi động và HMR nhanh hơn Webpack 10-20x.
Webpack: Bundle → serve (càng nhiều code, càng chậm)
Vite: Serve native ESM → transform on demand (nhanh bất kể project size)plaintextTại Sao Vite?#
Vấn Đề với Webpack#
Khi project lớn dần, Webpack chậm dần:
100 files → 5s dev start
1000 files → 30s dev start
10000+ → 2-5 phút dev start + HMR chậmplaintextVì Webpack bundle mọi thứ trước khi serve.
Vite Approach#
Vite dùng native ES modules của browser. Trình duyệt tải modules trực tiếp:
<!-- Vite dev: trình duyệt tải từng module riêng -->
<script type="module" src="/src/main.tsx"></script>
<script type="module" src="/src/App.tsx"></script>
<script type="module" src="/src/components/Header.tsx"></script>htmlKhông bundle — chỉ transform file khi trình duyệt request.
Setup#
npm create vite@latest my-project
# Select: React, Vue, Svelte, Vanilla, Lit...
cd my-project
npm install
npm run devbash# Templates
npm create vite@latest my-app -- --template react-ts
npm create vite@latest my-api -- --template vanilla-ts
npm create vite@latest my-vue -- --template vue-tsbashConfig#
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
open: true,
proxy: {
'/api': 'http://localhost:8080',
},
},
build: {
outDir: 'dist',
sourcemap: true,
minify: 'esbuild',
target: 'es2020',
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
},
},
},
},
})typescriptHMR (Hot Module Replacement)#
Vite HMR nhanh vì chỉ cần thay thế module đã thay đổi — không rebuild cả bundle:
Webpack HMR:
[file changed] → rebuild bundle → gửi new bundle → replace
Vite HMR:
[file changed] → transform 1 file → gửi file → replaceplaintextKết quả: HMR dưới 50ms cho mọi project size.
TypeScript#
Vite hỗ trợ TypeScript native — không cần cấu hình:
// Chạy TypeScript trực tiếp
// Vite dùng esbuild để transpile — nhanh hơn tsc 20-30xtypescript# esbuild transpile ~50ms per file
# tsc transpile ~1000ms per filebashTuy nhiên Vite không type-check — dùng tsc --noEmit riêng:
{
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview"
}
}jsonCSS & Preprocessors#
// vite.config.ts
import tailwind from '@tailwindcss/vite'
export default defineConfig({
plugins: [
tailwind(), // Tailwind CSS v4
],
css: {
modules: { localsConvention: 'camelCase' },
preprocessorOptions: {
scss: {
additionalData: `@import "./src/styles/variables";`,
},
},
},
})typescriptStatic Assets#
// Import asset → URL string
import logo from './assets/logo.png'
// logo = '/assets/logo.abc123.png'
// Dynamic import
const url = new URL('./images/hero.jpg', import.meta.url).href
// Public directory (copy as-is)
// public/favicon.ico → /favicon.icotypescriptEnvironment Variables#
// .env
VITE_API_URL=https://api.example.com
VITE_GOOGLE_ANALYTICS_ID=G-XXXXX
// src/env.d.ts
/// <reference types="vite/client" />
// Dùng trong code
const api = fetch(`${import.meta.env.VITE_API_URL}/data`)typescript// .env.development — dev only
// .env.production — build only
// .env.local — local override (gitignored)typescriptPlugins#
Vite có ecosystem plugin lớn, tương thích Rollup:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import vue from '@vitejs/plugin-vue'
import svelte from '@vitejs/plugin-svelte'
import solid from 'vite-plugin-solid'
import mdx from '@mdx-js/rollup'
export default defineConfig({
plugins: [
react(),
// Hoặc chọn một:
// vue(), svelte(), solid(),
{
// Custom plugin
name: 'my-plugin',
transform(code, id) {
if (id.endsWith('.custom')) {
return transformCustomFile(code)
}
},
},
],
})typescriptBuild cho Production#
npm run build
# dist/ — build outputbashVite dùng Rollup cho production build — tree-shaking, code splitting, minify:
// Dynamic import → automatic code splitting
const AdminPage = () => import('./pages/Admin.tsx')
// → admin.abc123.js (lazy load)
// manualChunks config
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('react')) return 'vendor-react'
if (id.includes('lodash')) return 'vendor-lodash'
return 'vendor'
}
},
},
},
}typescriptLibrary Mode#
Vite build cho thư viện — xuất ESM, CJS, UMD:
import { defineConfig } from 'vite'
export default defineConfig({
build: {
lib: {
entry: 'src/index.ts',
name: 'MyLib',
formats: ['es', 'cjs', 'umd'],
fileName: (format) => `my-lib.${format}.js`,
},
rollupOptions: {
external: ['react', 'react-dom'],
output: {
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
},
},
},
})typescriptnpm run build
# dist/my-lib.es.js
# dist/my-lib.cjs.js
# dist/my-lib.umd.jsbashSSR#
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
ssr: {
external: ['react', 'react-dom'],
noExternal: ['some-local-lib'],
},
})typescript// server.js (Node)
import { createServer } from 'vite'
const vite = await createServer({ server: { middlewareMode: true } })
const app = express()
app.use(vite.middlewares)typescriptSo Sánh#
| Webpack | Vite | |
|---|---|---|
| Dev start | 10-60s | <1s |
| HMR | 1-5s | <50ms |
| Config | Phức tạp | Đơn giản |
| TypeScript | Loader config | Native |
| CSS | Loader config | Native |
| Build | Webpack bundle | Rollup |
| Dev server | Express | Connect + ESM |
| Plugin ecosystem | Lớn | Lớn (Rollup compatible) |
Migration từ Webpack#
npm uninstall webpack webpack-cli webpack-dev-server
npm install -D vite @vitejs/plugin-reactbash// webpack.config.js → vite.config.ts
// Thường đơn giản hơn 70-80%typescript| Webpack | Vite |
|---|---|
babel-loader | @vitejs/plugin-react |
ts-loader | Native (esbuild) |
css-loader + style-loader | Native |
sass-loader | sass + css.preprocessorOptions |
html-webpack-plugin | Native |
copy-webpack-plugin | public/ directory |
Khi Nào Dùng Vite?#
✅ Nên dùng#
- Dự án mới — React, Vue, Svelte, Solid, Lit
- Monorepo — Turborepo, Nx với Vite
- Library build — ESM/CJS/UMD output
- SSR app — hỗ trợ tốt cho server rendering
- Web component — Lit, Stencil
❌ Không nên#
- Legacy project — migration từ Webpack quá lớn có thể không đáng
- Cần IE11 support — Vite target ES2015+
- Custom build pipeline phức tạp — Webpack flexibility cao hơn
Tổng Kết#
Vite thay đổi dev experience cho web developer.
# Vite: 3 lệnh là xong
npm create vite@latest my-app -- --template react-ts
cd my-app
npm run dev
# → Dev server trong 1 giâybash| Webpack 2018 | Vite 2026 | |
|---|---|---|
npm run dev | ~30s chờ bundle | ~300ms |
| Sửa 1 dòng code | ~3s HMR | ~30ms HMR |
| Config | 50+ dòng | 10-20 dòng |
| Build | 2-5 phút | 10-30s |
Vite là lựa chọn mặc định cho web development hiện tại — nhanh hơn, đơn giản hơn, TypeScript-native.