404 Not Found

404 Not Found


nginx

Vue 3 Vite プロジェクトの設定:`vite.config.ts`、SCSS、自動インポート、およびビルド最適化に関する包括的なガイド

Viteは、Vue 3チームによってリリースされた次世代のビルドツールであり、Webpackに比べて30倍も高速なコールドスタートを実現しています。Vite 5/6では、TypeScript、SSR、ビルドの最適化などの分野で大幅な改善がなされており、現代のVueプロジェクトにおける標準的な選択肢となっています。

このレッスンでは、Vite 5/6 のエンジニアリング設定全般について解説します:vite.config.ts、エイリアス、環境変数、SCSS、自動インポート、ビルドの最適化。これらは、エンタープライズレベルの Vue プロジェクトにおいて不可欠なスキルです。

1. 学習内容


2. 5分間のコールドスタート時の「エンジニア体験」の比較

(1) 課題:Webpackのコールドスタートに30秒かかり、開発者はクラッシュするのを待つ羽目になる

アリスのチームはWebpackを使用しました:

BASH
# Webpack Project Cold Start
$ npm run dev
> Project is running at http://localhost:8080
> Compiled successfully in 28.5s ← Waited 30s

チームリーダーのチャーリー:

「アリス、うちの開発サーバーの起動に30秒かかるんだ。ファイルを保存するたびに、ホットリロードに3秒かかる。Viteに切り替えるべきだ。」

(2) Vite Solution:5秒のコールドスタート、ミリ秒レベルのHMR

BASH
# Vite Project Cold Start
$ npm run dev
> VITE v5.4.0 ready in 487 ms ← Only 0.5s
> Local: http://localhost:5173/

開発経験の比較

動作 Webpack 5 Vite 5
コールドスタート 28秒 0.5秒
高、中、低 1~3秒 50ミリ秒未満
大規模プロジェクトの構築 30~60秒 5~15秒

コールドスタートが56倍高速化。Viteへの移行以来、開発効率が大幅に向上しました。

(3) 収益

Vite に切り替えた後:


3. Viteの主要な概念 5/6

(1) Vite デュアルモード

TEXT
Development Mode(dev):
 - Using native ESM,Directly in the browser import
 - Compile on Demand(Compiled only on the first visit to the page)
 - HMR Extremely fast(Update only the modules that have been modified)

Production Model(build):
 - Use Rollup Packaging
 - Automatic tree-shaking / Code Break / Compression
 - Output to dist/ Table of Contents

(2) 5つの主な利点

利点 説明
超高速コールドスタート esbuildが依存関係を事前にビルド(Go言語で記述されており、JSで記述されたBabelよりも100倍高速)
オンデマンドコンパイル 現在アクセスされているモジュールのみをコンパイルし、プロジェクト全体をコンパイルすることはありません
ネイティブ ESM ブラウザによって直接読み込まれる <script type="module">
HMR (Hyper-Fast) 1つのファイルを変更;この1つのモジュールのみが更新される
SSR / SSG 最高水準のサポート(Nuxt 3が公式に推奨)

(3) Vite 5/6 対 Vite 4

寸法 Vite 4 Vite 5/6
起動速度 高速 さらに高速(最適化された事前構築済み依存関係)
ビルド時間 5~15秒 3~8秒
Nodeの要件 14歳以上 18歳以上
ロールアップ 3.x 4.x
デフォルトのESM
評価 古い ⭐⭐⭐⭐⭐

4. vite.config.ts の設定を完了する

(1) 基本構造

TS
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig({
 // Project Root Directory(Default process.cwd())
 root: '.',
 
 // Basic Public Paths
 base: '/',
 
 // Plugins
 plugins: [vue()],
 
 // Server Configuration
 server: {
 port: 5173,
 open: true, // Open the browser automatically
 host: '0.0.0.0' // Accessible on the local area network
 },
 
 // Build Configuration
 build: {
 outDir: 'dist',
 sourcemap: false,
 minify: 'esbuild'
 },
 
 // CSS Layout
 css: {
 preprocessorOptions: {
 scss: {
 additionalData: `@import "@/styles/variables.scss";`
 }
 }
 },
 
 // Path Aliases
 resolve: {
 alias: {
 '@': path.resolve(__dirname, 'src')
 }
 }
})

(2) 5つの主な特徴

TS
export default defineConfig({
 // 1. Path Aliases(Most Commonly Used)
 resolve: {
 alias: {
 '@': path.resolve(__dirname, 'src'),
 '@components': path.resolve(__dirname, 'src/components'),
 '@stores': path.resolve(__dirname, 'src/stores')
 }
 },
 
 // 2. Server Configuration
 server: {
 port: 5173,
 open: true,
 host: '0.0.0.0',
 proxy: {
 '/api': {
 target: 'http://localhost:3000',
 changeOrigin: true
 }
 }
 },
 
 // 3. CSS Preprocessor
 css: {
 preprocessorOptions: {
 scss: { /* ... */ },
 less: { /* ... */ }
 }
 },
 
 // 4. Build Optimization
 build: {
 rollupOptions: {
 output: {
 manualChunks: {
 'vue-vendor': ['vue', 'vue-router', 'pinia']
 }
 }
 },
 chunkSizeWarningLimit: 1500
 },
 
 // 5. Optimization Options
 optimizeDeps: {
 include: ['vue', 'vue-router', 'pinia']
 }
})

5. 環境変数の3つの種類

(1) VITE_ プレフィックス規則

BASH
# .env.development
VITE_API_BASE_URL=http://localhost:3000
VITE_APP_TITLE=My App (Dev)

# .env.production
VITE_API_BASE_URL=https://api.example.com
VITE_APP_TITLE=My App

# .env.local(git Ignore,Each developer's own)
VITE_API_KEY=secret-key

(2) TypeScriptの型定義

TS
// src/env.d.ts
/// <reference types="vite/client" />

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

interface ImportMeta {
 readonly env: ImportMetaEnv
}

(3) コンポーネント内での使用

TS
const apiUrl = import.meta.env.VITE_API_BASE_URL
const title = import.meta.env.VITE_APP_TITLE

(4) 4つの.envファイルの優先順位

ファイル 用途 Git
.env すべての環境で共有 送信
.env.development 開発用のみ 送信
.env.production 制作専用 送信
.env.local ローカルでの上書き (コミットしない) 無視

6. SCSSの統合

(1) インストール

BASH
npm install -D sass

(2) グローバル変数

SCSS
// src/styles/variables.scss
$primary: #42b883;
$danger: #ef4444;
$font-size-base: 14px;
$border-radius: 4px;
TS
// vite.config.ts
css: {
 preprocessorOptions: {
 scss: {
 // Automatically import into each .scss Documents
 additionalData: `@import "@/styles/variables.scss";`
 }
 }
}
SCSS
// Any .scss You can use them directly in the document
.button {
 background: $primary; /* Not required @import */
 color: white;
 border-radius: $border-radius;
}

(3) SCSSの5つの主な利点


7. unplugin-auto-import 自動インポート

(1) インストール

BASH
npm install -D unplugin-auto-import

(2) 設定

TS
// vite.config.ts
import AutoImport from 'unplugin-auto-import'

export default defineConfig({
 plugins: [
 vue(),
 AutoImport({
 imports: ['vue', 'vue-router', 'pinia'],
 dts: 'src/auto-imports.d.ts', // Type Definitions
 eslintrc: {
 enabled: true // Generate .eslintrc-auto-import.json
 }
 })
 ]
})

(3) 使い方

VUE
<script setup>
// ✅ No longer needed import ref / computed / watch
const count = ref(0)
const double = computed(() => count.value * 2)
watch(count, (val) => console.log(val))

// ✅ No longer needed useRouter
const router = useRouter()
</script>

(4) 5つの主な利点

利点 説明
輸入量が減少 毎回 import ref / computed と入力する必要がない
型安全性 DTSファイルの自動型生成
設定可能 自動的にインポートするAPIを指定する
ESLint との互換性 インポートに関する警告を回避するために .eslintrc を自動生成
高速ビルド ビルド速度には影響しません

8. ビルドの最適化に関する5つの主要なポイント

(1) コードのチャンク化 (manualChunks)

TS
// vite.config.ts
build: {
 rollupOptions: {
 output: {
 manualChunks: {
 'vue-vendor': ['vue', 'vue-router', 'pinia'],
 'echarts-vendor': ['echarts', 'vue-echarts'],
 'utils': ['axios', 'dayjs']
 }
 }
 }
}

(2) ツリーシェイク(デフォルトで有効)

TS
build: {
 rollupOptions: {
 treeshake: {
 moduleSideEffects: 'no-external', // Mark all modules as side-effect-free
 propertyReadSideEffects: false // Reading tag attributes has no side effects
 }
 }
}

(3) CSSのミニフィケーション

TS
build: {
 cssMinify: 'lightningcss', // 10x faster than esbuild
 // or 'esbuild' (Default)
}

(4) リソースの取り扱い

TS
build: {
 assetsInlineLimit: 4096, // < 4KB Resources inline(base64)
 rollupOptions: {
 output: {
 assetFileNames: 'assets/[name]-[hash][extname]',
 chunkFileNames: 'js/[name]-[hash].js',
 entryFileNames: 'js/[name]-[hash].js'
 }
 }
}

(5) ソースマップ(本番環境でのデバッグ)

TS
build: {
 sourcemap: true, // Generated in the production environment as well(Used for Sentry)
 rollupOptions: {
 output: {
 sourcemapExcludeSources: true // Not including the source code inline into map
 }
 }
}

9. 完全な例:Viteの5つの主要な設定シナリオ

(1) ▶ サンプル:. vite.config.ts を完成させる

TS
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import'
import path from 'path'

export default defineConfig({
 plugins: [
 vue(),
 AutoImport({
 imports: ['vue', 'vue-router', 'pinia'],
 dts: 'src/auto-imports.d.ts'
 })
 ],
 
 resolve: {
 alias: {
 '@': path.resolve(__dirname, 'src')
 }
 },
 
 server: {
 port: 5173,
 open: true,
 proxy: {
 '/api': {
 target: 'http://localhost:3000',
 changeOrigin: true
 }
 }
 },
 
 css: {
 preprocessorOptions: {
 scss: {
 additionalData: `@import "@/styles/variables.scss";`
 }
 }
 },
 
 build: {
 outDir: 'dist',
 sourcemap: true,
 rollupOptions: {
 output: {
 manualChunks: {
 'vue-vendor': ['vue', 'vue-router', 'pinia']
 }
 }
 }
 }
})
▶ 試してみよう

(2) ▶ サンプル:. 環境変数の設定の3つのタイプ

BASH
# .env.development
VITE_API_BASE_URL=http://localhost:3000

# .env.production
VITE_API_BASE_URL=https://api.example.com

# .env.local
VITE_API_KEY=secret
TS
// src/env.d.ts
interface ImportMetaEnv {
 readonly VITE_API_BASE_URL: string
 readonly VITE_API_KEY?: string
}
interface ImportMeta {
 readonly env: ImportMetaEnv
}
TS
// Usage
const apiUrl = import.meta.env.VITE_API_BASE_URL

(3) ▶ サンプル:. ビルドの最適化に関する5つの主要なポイント

最適化 設定
コードチャンク マニュアルチャンク
ツリーシェイク ツリーシェイクの設定
CSSのミニフィケーション cssMinify: 'lightningcss'
リソース処理 assetsInlineLimit + ファイル名
ソースマップ sourcemap: true

(4) ▶ サンプル:. よくある5つの間違いに関するクイックリファレンス

エラー 症状 解決策
パスエイリアスが機能していない インポートに失敗しました path.resolve が __dirname を使用しています
未定義の SCSS 変数 コンパイルエラー additionalData の自動インポート
環境変数が未定義 実行時に未定義 「VITE_」という接頭辞を使用し、.env ファイルを活用する
自動インポートが機能しない 参照が見つかりません DTSファイルの生成を確認してください
本番環境で画面が真っ白になる パスエラー base: '/yourpath/' の設定

(5) ▶ サンプル:. 5つの主要なViteのパフォーマンス比較

構成 コールドスタート HMR 本番ビルド
デフォルト 0.5秒 50ミリ秒 10秒
+ エイリアス 0.5秒 50ミリ秒 10秒
+ SCSS 0.6秒 60ミリ秒 11秒
+ 自動インポート 0.6秒 60ミリ秒 11秒
+ manualChunks 0.6秒 60ミリ秒 12秒(ただし、最初の画面の表示は50%高速)

❓ よくある質問

Q Vite 5/6 の最小 Node バージョンは何ですか?
A Node 18 以上(2023年10月現在)。Node 16 はサポート終了(EOL)となっています。Vite 4 では引き続き Node 14 以上がサポートされています。
Q ESMでpath.resolveから__dirnameをどのように使用しますか?
A import.meta.url:fileURLToPath(new URL('./src', import.meta.url))を使用します。Vite 5では、resolve.aliaspath.resolveと組み合わせて使用することが推奨されています。
Q 環境変数には「VITE_」という接頭辞が必要ですか?
A はい。デフォルトでは、Vite は(セキュリティ上の理由から)「VITE_」という接頭辞が付いた変数のみを公開します。それ以外の変数はバンドルされません。
Q 自動インポートは本番環境でも使用できますか?
A はい。unplugin-auto-import はビルド時に自動インポートのコードを削除し(明示的なインポートに置き換えます)、バンドリング処理に影響を与えません。
Q ViteとWebpack、どちらを選べばいいですか?
A 新しいプロジェクトにはすべてViteを使用してください。Webpackは既存のプロジェクトのメンテナンスにのみ使用します。Viteはコールドスタートが30倍速く、HMRの処理も60倍速いです。
Q ViteのSSRはどのように設定すればよいですか?
A vite build --ssr または Nuxt 3 を使って統合してください。SSRの設定は少々複雑ですが(ハイドレーションの処理が必要になります)、Viteには充実した公式サポートが用意されています。
Q unplugin-auto-import の dts ファイルはいつ生成されますか?
A 開発サーバーの起動時およびビルド処理中に生成されます。また、npx auto-imports を手動で実行して生成することもできます。

📖 まとめ


📝 練習問題

(1) 基礎問題(難易度:⭐)

以下の設定で Vite + Vue 3 プロジェクトを作成します:

(2) 上級問題(難易度:⭐⭐)

Viteの設定を完了する:

(3) チャレンジ問題(難易度:⭐⭐⭐)

完全な「エンタープライズグレードのVite設定」を実装する:

  1. 5つの主要なパスエイリアス(@ / @components / @stores / @utils / @composables)
  2. SCSSのグローバル変数と5つのミックスイン(flex / card / button / form / responsive)
  3. unplugin-auto-import + Volar スタイルでの生成
  4. 3種類の環境変数(dev / staging / prod)
  5. 5 ビルドの最適化(manualChunks / ツリーシェイク / lightningcss / / ソースマップ)
  6. バックエンドへのプロキシ /api
  7. TypeScript の完全な設定(env.d.ts + auto-imports.d.ts)
Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%