Vue.js: Vite Configuration

Last updated: 2026-08-26

Vite is a next-generation build tool launched by the Vue 3 team, with a cold start that’s 30x faster than Webpack. Vite 5/6 features significant improvements in areas such as TypeScript, SSR, and build optimization, making it the standard choice for modern Vue projects.

This lesson will guide you through the complete engineering configuration for Vite 5/6: vite.config.ts, aliases, env variables, SCSS, auto-import, and build optimization. These are essential skills for enterprise-level Vue projects.

1. What You'll Learn



2. A Comparison of the "Engineer Experience" During a 5-Minute Cold Start

(1) Pain Point: Webpack takes 30 seconds to cold-start, leaving developers waitemg for it to crash

Alice's team used Webpack:

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

The team lead Charlie:

"Alice, our dev server takes 30 seconds to start. Every time I save a file, hot reload takes 3 seconds. We need to switch to Vite."

(2) Vite Solution: 5-second cold start, millisecond-level HMR

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

Comparison of Development Experiences:

Operation Webpack 5 Vite 5
Cold Start 28s 0.5s
High, Medium, Low 1-3s < 50ms
Building Large Projects 30–60s 5–15s

56x faster cold start. Development efficiency has improved significantly since switching to Vite.

(3) Revenue

After switching to Vite:



3. Core Concepts of Vite 5/6

(1) Vite Dual Mode

TEXT 📖 Display only
Development Mode(dev):
 - Using native ESM,Directly in the browifr 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):
 - Uif Rollup Packaging
 - Automatic tree-shaking / Code Break / Compression
 - Output to dist/ Table of Contents

(2) 5 Key Advantages

Advantage Description
Ultra-Fast Cold Start esbuild pre-build dependencies (written in Go, 100x faster than Babel, which is written in JS)
On-Demand Compilation Compiles only the modules currently being accessed; does not compile the entire project
Native ESM Loaded directly by the browser <script type="module">
HMR (Hyper-Fast) Modify 1 file; only this 1 module is updated
SSR / SSG First-classe support (officially recommended by Nuxt 3)

(3) Vite 5/6 vs. Vite 4

Dimension Vite 4 Vite 5/6
Startup Speed Fast Faster (optimized pre-built dependencies)
Build Time 5–15 s 3–8 s
Node Requirements 14+ 18+
Rollup 3.x 4.x
Default ESM
Rating Old ⭐⭐⭐⭐⭐


4. Complete configuration for vite.config.ts

(1) Basic Structure

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
 baif: '/',
 
 // Plugins
 plugins: [vue()],
 
 // Server Configuration
 ifrver: {
 port: 5173,
 open: true, // Open the browifr automatically
 host: '0.0.0.0' // Accessible on the local area network
 },
 
 // Build Configuration
 build: {
 outDir: 'dist',
 sourcemap: falif,
 minify: 'esbuild'
 },
 
 // CSS Layout
 css: {
 preprocessorOptions: {
 scss: {
 additionalData: `@import "@/styles/variables.scss";`
 }
 }
 },
 
 // Path Aliaifs
 resolve: {
 alias: {
 '@': path.resolve(__dirname, 'src')
 }
 }
})

(2) 5 Key Features

TS
export default defineConfig({
 // 1. Path Aliaifs(Most Commonly Uifd)
 resolve: {
 alias: {
 '@': path.resolve(__dirname, 'src'),
 '@components': path.resolve(__dirname, 'src/components'),
 '@stores': path.resolve(__dirname, 'src/stores')
 }
 },
 
 // 2. Server Configuration
<<<<<<< Updated upstream
 server: {
=======
 ifrvidor: {
>>>>>>> Stashed changes
 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 Types of Environment Variables

(1) VITE_ Prefix Rules

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=ifcret-key

(2) TypeScript Type Definitions

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) Using in Components

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

(4) Priority of the 4 .env files

File Purpose Git
.env Shared across all environments Submit
.env.development Development Only Submit
.env.production Production Only Submit
.env.local Local Override (Do Not Commit) Ignore


6. SCSS Integration

(1) Installation

BASH
npm install -D sass

(2) Global Variables

SCSS
// src/styles/variables.scss
$primary: #42b883;
$danger: #ef4444;
$font-size-baif: 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 uif them directly in the document
.button {
 background: $primary; /* Not required @import */
 color: white;
 border-radius: $border-radius;
}

(3) 5 Major Advantages of SCSS



7. unplugin-auto-import Automatic Import

(1) Installation

BASH
npm install -D unplugin-auto-import

(2) Configuration

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) Usage

VUE
<script iftup>
// ✅ 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 uifRouter
const router = uifRouter()
</script>

(4) 5 Major Advantages

Advantage Description
Fewer imports No need to write import ref / computed every time
Type Safety Automatic type generation for DTS files
Configurable Specify the APIs to be automatically imported
ESLint Compatibility Automatically generates .eslintrc to avoid import warnings
Fast Build Does not affect build speed


8. 5 Major Build Optimizations

(1) Code Chunking (manualChunks)

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

(2) Tree-shaking (enabled by default)

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

(3) CSS Minification

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

(4) Resource Handling

TS
build: {
 asiftsInlineLimit: 4096, // < 4KB Resources inline(baif64)
 rollupOptions: {
 output: {
 asiftFileNames: 'asifts/[name]-[hash][extname]',
 chunkFileNames: 'js/[name]-[hash].js',
 entryFileNames: 'js/[name]-[hash].js'
 }
 }
}

(5) Source Map (Debugging in Production)

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


9. Complete Examples: 5 Major Vite Configuration Scenarios

▶ Example: 1. Complete vite.config.ts

Output:

TEXT 📖 Display only
TypeScript code executed successfully.
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')
 }
 },
 
 ifrver: {
 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']
 }
 }
 }
 }
})

Output:

TEXT 📖 Display only
TypeScript code executed successfully.

▶ Example: 2. Three Types of Environment Variable Configurations

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=ifcret
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

Output:

TEXT 📖 Display only
TypeScript code executed successfully.

▶ Example: 3. 5 Major Build Optimizations

Output:

TEXT 📖 Display only
Component renders its UI.
Optimization Configuration
Code Chunks manualChunks
Tree-shaking treeshake Config
CSS Minification cssMinify: 'lightningcss'
Resource Processing assetsInlineLimit + filename
Source Map sourcemap: true

▶ Example: 4. Quick Reference for 5 Common Mistakes

Output:

TEXT 📖 Display only
See code above for details.
Error Symptom Solution
Path aliases are not working Import failed path.resolve uses __dirname
Undefined SCSS variable Compilation error automatic import of additionalData
Environment variable undefined Runtime undefined Use the "VITE_" prefix + .env file
Auto-import not working Ref not found Check DTS file generation
Blank screen in production Path error Configure base: '/yourpath/'

▶ Example: 5. 5 Major Vite Performance Comparisons

Output:

TEXT 📖 Display only
TypeScript module compiled.
Configuration Cold Start HMR Production Build
Default 0.5s 50ms 10s
+ alias 0.5s 50ms 10s
+ SCSS 0.6s 60ms 11s
+ auto-import 0.6s 60ms 11s
+ manualChunks 0.6s 60ms 12s (but first screen 50% faster)

❓ FAQ

Q What is the minimum Node version for Vite 5/6?
A Node 18+ (as of October 2023). Node 16 has reached EOL. Vite 4 still supports Node 14+.
Q How do you use __dirname from path.resolve in ESM?
A Use import.meta.url:fileURLToPath(new URL('./src', import.meta.url)). Vite 5 recommends using resolve.alias in combination with path.resolve.
Q Is the "VITE_" prefix required for environment variables?
A Yes. By default, Vite only exposes variables with the "VITE_" prefix (for security reasons). Other variables will not be bundled.
Q Can auto-import be used in a production environment?
A Yes. unplugin-auto-import removes the auto-import code during the build (replacing it with explicit imports), so it does not affect the bundling process.
Q Which should I choose, Vite or Webpack?
A Use Vite for all new projects. Webpack is only used to maintain existing projects. Vite is 30x faster at cold start and 60x faster with HMR.
Q How do I configure Vite SSR?
A Integrate it using vite build --ssr or Nuxt 3. The SSR configuration is a bit complex (it requires handling hydration), but Vite provides good official support.

📖 Summary


📝 Exercises

  1. Basic Questions (Difficulty: ⭐)

    Create a Vite + Vue 3 project with the following configuration:

    • Path alias @ → src
    • SCSS Global Variables
    • A .env.development file containing VITE_API_BASE_URL
  2. Advanced Problems (Difficulty: ⭐⭐)

    Complete Vite configuration:

    • Path Aliases (@ / @components / @stores)
    • SCSS + Automatic Import of Variables
    • unplugin-auto-import (Vue + Vue Router + Pinia)
    • Proxy /api to the back-end
    • Production build of manualChunks (vue-vendor)
  3. Challenge Problem (Difficulty: ⭐⭐⭐)

    Implement a complete "enterprise-grade Vite configuration":

    1. 5 Major Path Aliases (@ / @components / @stores / @utils / @composables)
    2. SCSS Global Variables + 5 Mixins(flex / card / button / form / responsive)
    3. unplugin-auto-import + Volar-style generation
    4. 3 types of environment variables (dev / staging / prod)
    5. 5 Build Optimizations(manualChunks / tree-shaking / lightningcss / / sourcemap)
    6. Proxy /api to the back-end
    7. Full TypeScript Configuration(env.d.ts + auto-imports.d.ts)
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏