vite の使い方

Native-ESM powered web dev build tool

v8.0.390.0M/週MITビルドツール
AI生成コンテンツ

この記事はAIによって生成されました。内容の正確性は保証されません。最新の情報は公式ドキュメントをご確認ください。

Vite の使い方完全ガイド — 次世代フロントエンドビルドツール

一言でいうと

Viteは、ネイティブES Modulesを活用した超高速な開発サーバーと、Rollupベースの最適化されたプロダクションビルドを提供するフロントエンドビルドツールです。開発時のサーバー起動とHMR(Hot Module Replacement)が圧倒的に速く、モダンフロントエンド開発のデファクトスタンダードとなっています。

※ 本記事は Vite 8.0.3 を対象としています。メジャーバージョンによってAPIや設定が異なる場合があります。

どんな時に使う?

  1. React / Vue / Svelte などのSPAプロジェクトの開発環境構築 — webpack の設定地獄から解放され、ゼロコンフィグに近い形で高速な開発体験を得たいとき
  2. ライブラリのビルド — ライブラリモードを使って、ESM / CJS / UMD 形式のバンドルを簡単に出力したいとき
  3. 既存プロジェクトのビルドツール移行 — webpack や Create React App からの移行で、ビルド速度とDXを大幅に改善したいとき

インストール

# npm
npm install -D vite

# yarn
yarn add -D vite

# pnpm
pnpm add -D vite

プロジェクトのスキャフォールディング(新規作成)

# npm
npm create vite@latest my-app

# pnpm
pnpm create vite my-app

# yarn
yarn create vite my-app

対話形式でフレームワーク(React, Vue, Svelte, Solid, etc.)とTypeScript/JavaScriptの選択ができます。

基本的な使い方

プロジェクト構成

my-app/
├── index.html          # エントリーポイント(publicではなくルート直下)
├── src/
│   ├── main.ts
│   └── App.tsx
├── public/
│   └── favicon.ico
├── vite.config.ts
├── tsconfig.json
└── package.json

vite.config.ts の基本設定

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true,
  },
  build: {
    outDir: 'dist',
    sourcemap: true,
  },
})

package.json のスクリプト

{
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  }
}

index.html

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Vite App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

Viteでは index.html がエントリーポイントであり、<script type="module"> でソースファイルを直接参照するのが特徴です。

よく使うAPI — Vite の使い方を深掘り

1. 環境変数の利用

Viteは .env ファイルをサポートしています。VITE_ プレフィックスが付いた変数のみクライアントコードに公開されます。

# .env
VITE_API_BASE_URL=https://api.example.com
VITE_APP_TITLE=My App
// src/env.d.ts — 型定義
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_BASE_URL: string
  readonly VITE_APP_TITLE: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}
// src/api.ts
const baseUrl = import.meta.env.VITE_API_BASE_URL

export async function fetchUsers() {
  const res = await fetch(`${baseUrl}/users`)
  return res.json()
}

// モード判定
if (import.meta.env.DEV) {
  console.log('開発モードです')
}

2. プロキシ設定(API連携)

開発時にバックエンドAPIへのリクエストをプロキシする設定です。CORS問題を回避できます。

import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    proxy: {
      // /api/xxx → http://localhost:8080/api/xxx
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
      // /ws → WebSocketプロキシ
      '/ws': {
        target: 'ws://localhost:8080',
        ws: true,
      },
      // パスの書き換え: /fallback/xxx → http://localhost:8080/xxx
      '/fallback': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/fallback/, ''),
      },
    },
  },
})

3. CSS / CSS Modules / PostCSS

Viteは CSS Modules、Sass、Less、PostCSS をビルトインでサポートしています。

// CSS Modules(.module.css で自動認識)
import styles from './Button.module.css'

function Button() {
  return <button className={styles.primary}>Click me</button>
}
// vite.config.ts — CSS設定のカスタマイズ
import { defineConfig } from 'vite'

export default defineConfig({
  css: {
    modules: {
      localsConvention: 'camelCaseOnly', // kebab-case → camelCase
    },
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/styles/variables" as *;`,
      },
    },
    postcss: './postcss.config.js',
  },
})

4. 静的アセットの取り扱い

// デフォルト: URLとしてインポート
import logoUrl from './assets/logo.png'
// → "/assets/logo.2d8efhg.png"(ビルド時にハッシュ付き)

// ?raw: 文字列としてインポート
import shaderCode from './shaders/fragment.glsl?raw'

// ?url: 明示的にURL取得
import workerUrl from './worker.ts?url'

// ?inline: インラインBase64
import iconInline from './icon.svg?inline'
// vite.config.ts — アセット閾値の設定
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    assetsInlineLimit: 4096, // 4KB未満はBase64インライン化
  },
})

5. JavaScript API(プログラマティックな利用)

Viteはプログラムから直接操作できるJavaScript APIを提供しています。カスタムCLIツールやテスト環境の構築に便利です。

import { createServer, build, preview } from 'vite'

// 開発サーバーをプログラムから起動
async function startDevServer() {
  const server = await createServer({
    configFile: './vite.config.ts',
    server: {
      port: 3000,
    },
  })
  await server.listen()
  server.printUrls()

  // サーバーの情報にアクセス
  console.log('Resolved config:', server.config.resolve.alias)
}

// プログラムからビルド実行
async function runBuild() {
  const output = await build({
    root: process.cwd(),
    build: {
      outDir: 'dist',
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['react', 'react-dom'],
          },
        },
      },
    },
  })
  console.log('Build complete:', output)
}

// プレビューサーバー起動
async function startPreview() {
  const previewServer = await preview({
    preview: {
      port: 4173,
      open: true,
    },
  })
  previewServer.printUrls()
}

6. プラグインの作成

Viteプラグインは Rollup プラグインの拡張であり、Vite固有のフックも利用できます。

import type { Plugin } from 'vite'

function myCustomPlugin(): Plugin {
  return {
    name: 'my-custom-plugin',

    // Vite固有: 設定の解決後に呼ばれる
    configResolved(config) {
      console.log('Root:', config.root)
      console.log('Mode:', config.mode)
    },

    // Vite固有: 開発サーバーのミドルウェア追加
    configureServer(server) {
      server.middlewares.use('/health', (_req, res) => {
        res.end('OK')
      })
    },

    // Rollup互換: モジュールの変換
    transform(code, id) {
      if (id.endsWith('.md')) {
        return {
          code: `export default ${JSON.stringify(code)}`,
          map: null,
        }
      }
    },
  }
}

// vite.config.ts で使用
export default defineConfig({
  plugins: [myCustomPlugin()],
})

類似パッケージとの比較

特徴VitewebpackesbuildTurbopack
開発サーバー起動速度◎ 極めて高速△ プロジェクト規模に依存◎ 極めて高速◎ 極めて高速
HMR速度△〜○- (サーバー機能なし)
プロダクションビルド○ Rollupベース○ 成熟◎ 最速△ 発展途上
プラグインエコシステム◎ Rollup互換 + 独自◎ 最大規模△ 限定的△ 発展途上
設定の容易さ◎ ゼロコンフィグ寄り△ 設定が複雑○ Next.js統合
TypeScriptサポート◎ ビルトイン△ 要loader設定◎ ビルトイン
SSR対応○ 実験的→安定化○ Next.js経由
採用実績◎ Vue/Svelte/Astro等◎ 最大○ ビルドツール内部○ Next.js

選定の目安:

  • 新規プロジェクト → Vite(最もバランスが良い)
  • 既存の大規模webpackプロジェクト → 段階的にViteへ移行を検討
  • Next.jsを使う場合 → Turbopack(Next.js組み込み)
  • ライブラリの超高速ビルドのみ → esbuild / tsup(Viteも内部でesbuildを使用)

注意点・Tips

1. index.html はルート直下に置く

webpackと異なり、Viteでは index.html がエントリーポイントです。public/ ではなくプロジェクトルートに配置してください。マルチページの場合は build.rollupOptions.input で複数エントリーを指定します。

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: 'index.html',
        admin: 'admin.html',
      },
    },
  },
})

2. CommonJS モジュールへの対応

Viteはネイティブ ESM ベースのため、CommonJS のみで配布されているパッケージは事前バンドル(依存関係の最適化)で自動変換されます。ただし、まれに問題が起きる場合は optimizeDeps で明示的に指定します。

export default defineConfig({
  optimizeDeps: {
    include: ['legacy-cjs-package'],
  },
})

3. パスエイリアスの設定

import { defineConfig } from 'vite'
import path from 'node:path'

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/components'),
    },
  },
})

tsconfig.jsonpaths とも整合性を取ることを忘れないでください。

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"]
    }
  }
}

4. ビルドターゲットに注意

Viteのデフォルトビルドターゲットはモダンブラウザ(ネイティブESMサポート)です。レガシーブラウザ対応が必要な場合は @vitejs/plugin-legacy を使用します。

import legacy from '@vitejs/plugin-legacy'

export default defineConfig({
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11'],
    }),
  ],
})

5. import.meta.envprocess.env の違い

Viteでは process.env はクライアントコードで使用できません。代わりに `

比較記事