Vite 03 設定とプラグイン

更新日:

vite.config.ts の基本

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from 'node:path'
 
export default defineConfig({
  plugins: [react(), tailwindcss()],
  resolve: {
    alias: { '@': path.resolve(__dirname, './src') },   // import '@/components/...'
  },
  server: {
    port: 3000,
    open: true,
    proxy: {
      // 開発中、/api へのリクエストをバックエンドへ転送(CORS 回避)
      '/api': {
        target: 'http://localhost:8787',
        changeOrigin: true,
      },
    },
  },
  build: {
    outDir: 'dist',
    sourcemap: true,
  },
})
  • defineConfig で囲むとエディタの補完が効く
  • エイリアスを使う時は tsconfig.json の paths も合わせる(型補完のため):
{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }

条件付き設定(開発と本番で変える)

export default defineConfig(({ command, mode }) => {
  if (command === 'serve') {
    return { /* 開発用 */ }
  }
  return { /* ビルド用 */ }
})
  • 設定ファイル内で .env を読むには loadEnv(mode, process.cwd())

よく使う設定項目

項目意味
pluginsプラグイン一覧
base公開パス(サブディレクトリに置く時 /my-app/)
resolve.aliasimport のエイリアス
server.port / host / open開発サーバー
server.proxyAPI への転送
server.allowedHosts開発サーバーにアクセスできるホスト名(トンネル利用時など)
build.outDir / sourcemap / targetビルド出力
envPrefix公開する環境変数の接頭辞(既定 VITE_)
css.modulesCSS Modules の設定

プラグイン

npm add -D @vitejs/plugin-react

代表的なもの:

プラグイン用途
@vitejs/plugin-reactReact(Fast Refresh)
@vitejs/plugin-react-swcReact(SWC 版)
@vitejs/plugin-rscReact Server Components
@vitejs/plugin-vueVue
@tailwindcss/viteTailwind CSS v4
@cloudflare/vite-pluginCloudflare Workers 実行環境で開発 → Cloudflare_05_フレームワーク連携とデプロイ
@tanstack/router-pluginTanStack Router のファイルベースルーティング
vite-plugin-checker型・lint エラーをブラウザに表示
vite-plugin-pwaPWA 化
  • 探す: 公式の Plugins ページ、awesome-vite
  • Rollup/Rolldown 用プラグインの多くもそのまま使える
  • apply: 'build' / 'serve' で片方だけ適用、enforce: 'pre' | 'post' で順序

開発サーバーの小技

  • vite --host で同じWi-Fi のスマホから確認(表示される Network の URL にアクセス)
  • server.warmup でよく使うファイルを事前変換(起動後の初回表示を速く)
  • server.forwardConsole: ブラウザのコンソールをターミナルに転送(AI エージェントにエラーを見せたい時に便利)

関連