Cấu hình môi trường

#Tại sao Vite thay vì CRA?

Create React App đã bị deprecated. Vite khởi động nhanh hơn 10–20x, bundle nhỏ hơn, và cấu hình dễ extend hơn.

npm create vite@latest my-app -- --template react-ts
cd my-app
npm install

#tsconfig.json quan trọng

Vite đã generate tsconfig.json nhưng có vài thứ nên điều chỉnh:

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  }
}

Hai option quan trọng nhất:

  • strict: true — bật hết mọi strict check. Đừng bao giờ tắt cái này.
  • noUnusedLocals / noUnusedParameters — bắt buộc cleanup code, tránh biến rác.

#Path aliases

Thêm vào tsconfig.jsonvite.config.ts để import đẹp hơn:

// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
// 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'),
    },
  },
})

Sau đó install type definitions:

npm install -D @types/node

Từ giờ có thể import @/components/Button thay vì ../../../components/Button.