mcpField
V
vite

vite

github.com/mindrally開発289839 回インストール3 週間前に更新
リポジトリ

vite について

JavaScript と TypeScript でフロントエンドを開発する人向けの Vite スキルです。プロジェクト設定から開発、アセット処理、本番ビルドまでを扱います。

主な機能

  1. 01Vite の設定と初期構築
  2. 02環境変数とパスエイリアス
  3. 03ホットモジュール置換
  4. 04アセットと CSS の処理
  5. 05ビルド最適化と SSR
  6. 06プラグイン開発

活用シーン

  1. 01Vite のフロントエンドプロジェクト構築
  2. 02React、Vue、Svelte プロジェクトの設定
  3. 03本番ビルドのチャンク調整
  4. 04プロキシや SSR の設定

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/mindrally/skills --skill vite

インストール後、Claude Code で/viteを入力して読み込まれたか確認します。

詳細

Vite 開発

Vite、最新の JavaScript/TypeScript ビルドツール、フロントエンド開発に精通しています。

主な原則

  • 高速な開発のためにネイティブ ES モジュールを活用します
  • 可能な限り Vite の意見に基づくデフォルト設定を使用します
  • カスタマイズが必要な項目だけを設定します
  • 開発時とビルド時の違いを理解します
  • 開発速度と本番環境のパフォーマンスの両方を最適化します

プロジェクトのセットアップ

基本設定
// 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,
  },
});
パスエイリアス
import { defineConfig } from 'vite';
import path from 'path';

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

環境変数

使用方法
// .env
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My App

// In code
const apiUrl = import.meta.env.VITE_API_URL;
const isDev = import.meta.env.DEV;
const isProd = import.meta.env.PROD;
const mode = import.meta.env.MODE;
型定義
// src/vite-env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_URL: string;
  readonly VITE_APP_TITLE: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

ホットモジュール置換

手動 HMR
// For libraries without HMR support
if (import.meta.hot) {
  import.meta.hot.accept('./module.ts', (newModule) => {
    // Handle the updated module
    console.log('Module updated:', newModule);
  });

  import.meta.hot.dispose(() => {
    // Cleanup before module is replaced
  });
}

アセットの処理

静的アセット
// Import as URL
import imageUrl from './image.png';
// <img src={imageUrl} />

// Import as string (raw)
import shaderCode from './shader.glsl?raw';

// Import as worker
import Worker from './worker.ts?worker';
const worker = new Worker();
パブリックディレクトリ
public/
├── favicon.ico      # Served at /favicon.ico
├── robots.txt       # Served at /robots.txt
└── images/          # Served at /images/

フレームワークとの統合

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

export default defineConfig({
  plugins: [
    react({
      // Enable Fast Refresh
      fastRefresh: true,
      // Babel plugins
      babel: {
        plugins: ['@emotion/babel-plugin'],
      },
    }),
  ],
});
Vue
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
});
Svelte
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';

export default defineConfig({
  plugins: [svelte()],
});

ビルドの最適化

コード分割
// Dynamic imports create separate chunks
const AdminPanel = lazy(() => import('./AdminPanel'));

// Manual chunks
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          utils: ['lodash', 'date-fns'],
        },
      },
    },
  },
});
チャンクサイズの最適化
export default defineConfig({
  build: {
    chunkSizeWarningLimit: 500,
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return id.split('node_modules/')[1].split('/')[0];
          }
        },
      },
    },
  },
});

CSS の処理

CSS モジュール
// styles.module.css is auto-detected
import styles from './styles.module.css';

// <div className={styles.container}>
PostCSS
// postcss.config.js
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
プリプロセッサー
// Automatically handled with package installed
// npm install -D sass
import './styles.scss';

プロキシ設定

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:4000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
      '/socket.io': {
        target: 'ws://localhost:4000',
        ws: true,
      },
    },
  },
});

プラグイン開発

// my-vite-plugin.ts
import type { Plugin } from 'vite';

export function myPlugin(): Plugin {
  return {
    name: 'my-plugin',

    // Hook: modify config
    config(config, { mode }) {
      return {
        define: {
          __BUILD_TIME__: JSON.stringify(new Date().toISOString()),
        },
      };
    },

    // Hook: transform code
    transform(code, id) {
      if (id.endsWith('.md')) {
        return {
          code: `export default ${JSON.stringify(code)}`,
          map: null,
        };
      }
    },

    // Hook: configure dev server
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        // Custom middleware
        next();
      });
    },
  };
}

Vitest を使ったテスト

// vite.config.ts
import { defineConfig } from 'vite';

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './src/test/setup.ts',
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});

SSR 設定

export default defineConfig({
  build: {
    ssr: true,
    rollupOptions: {
      input: './src/entry-server.ts',
    },
  },
  ssr: {
    external: ['express'],
    noExternal: ['my-ui-library'],
  },
});

ライブラリモード

export default defineConfig({
  build: {
    lib: {
      entry: './src/index.ts',
      name: 'MyLib',
      fileName: (format) => `my-lib.${format}.js`,
    },
    rollupOptions: {
      external: ['react', 'react-dom'],
      output: {
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM',
        },
      },
    },
  },
});

ベストプラクティス

  • vite preview を使用して、本番ビルドをローカルでテストします
  • ESM をサポートする依存関係は通常の依存関係に含めます
  • CommonJS の依存関係には optimizeDeps.include を使用します
  • 本番環境のデバッグには build.sourcemap を有効にします
  • 開発サーバーの起動を高速化するには server.warmup を使用します

コメント