Skip to content
Created: July 13, 2024

🎯 Table of contents (what you will learn from beginner to proficient) ​

  1. What is Vite & why is it so fast
  2. Get started quickly (create project, directory structure, basic configuration)
  3. index.html as the entry mechanism
  4. Development model principle: No-Bundle + ESM implementation
  5. Build mode principle: Rollup packaging optimization
  6. Detailed explanation of common configurations (vite.config.ts fully explained)
  7. Vite plug-in system (how to write plug-ins)
  8. Vite + Vue / React / TS / JSX
  9. Static resources, aliases, environment variables, cross-domain and other practical operations
  10. Performance Optimization (Development and Production)
  11. Vite source code intensive reading path (real proficiency)

🎉 1. What is Vite? ​

Vite is a front-end building tool developed by You Yuxi (Vue author).

Core features:

FeaturesViteWebpack
Development startupOpen in seconds (No-Bundle)Slow
HMR hot updateExtremely fast (update by module)Some bundles need to be rebuilt
BuildRollupWebpack package by yourself
Configuration complexitySimpleComplex

In a word: The development speed is the fastest in the industry and the build quality is the highest.

🚀 2. Get started quickly ​

✔ Create project ​

bash
npm create vite@latest

Choose a framework such as Vue/React.

✔ Install dependencies ​

bash
npm install

✔ Start the development server ​

bash
npm run dev

You will see:

Local: http://localhost:5173/

✔ Production build ​

bash
npm run build

📁 3. Project structure description ​

project/
 ├── index.html ← 最独特的地方,入口文件
 ├── src/
 │    ├── main.ts
 │    ├── App.vue
 └── vite.config.ts

index.html directly controls the entry script:

html
<script type="module" src="/src/main.ts"></script>

Unlike Webpack: Vite is centered around index.html rather than packaging entry files.

⚙️ 4. Principles of Vite development model (core) ​

⭐ Reason 1: Not packaging development code ​

Webpack:

打包 → 输出 bundle → 浏览器加载

Vite:

浏览器遇到 import → Vite 返回对应文件

Leveraging browser-native ESM:

js
import { createApp } from './src/main.js'

The browser automatically requests the environment:

/src/main.js

Vite does the most basic parsing of files (Vue, TS, React, CSS, etc.), but Not packed 。

Result: startup speed is independent of project size → starts in seconds ​

⭐ Reason 2: Ultra-fast HMR ​

Updating a file → reloads only the file, not the entire bundle.

Vue single file component updates are basically at the millisecond level.

🏗 5. Vite construction mode principle (Rollup) ​

When building for production:

  • Tree Shaking
  • code splitting
  • CSS extraction
  • Chunk split
  • Compression Minify
  • Assets processing

Delegate it all to Rollup (the best optimized bundler in the industry).

🔧 6. Detailed explanation of Vite configuration file (vite.config.ts) ​

The most basic:

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

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

Below are the configuration points from beginner to advanced.

✅ Commonly used configuration points ​

1. alias alias ​

ts
resolve: {
  alias: {
    '@': '/src'
  }
}

2. environment variables ​

Added .env.development / .env.production:

VITE_API_URL=https://xxx.com

Use:

js
import.meta.env.VITE_API_URL

3. Server proxy (solve cross-domain) ​

ts
server: {
  proxy: {
    '/api': {
      target: 'https://backend.com',
      changeOrigin: true,
      rewrite: p => p.replace(/^\/api/, '')
    }
  }
}

4. Static resources ​

If placed in the public/ root directory, it will not be packaged and will be copied directly as it is.

5. CSS and preprocessors ​

Support:

ts
css: {
  preprocessorOptions: {
    scss: {
      additionalData: `@import "@/styles/global.scss";`
    }
  }
}

6. Build optimization ​

ts
build: {
  sourcemap: false,
  minify: 'esbuild',
  rollupOptions: {
    output: {
      manualChunks: {
        vendor: ['vue']
      }
    }
  }
}

🔌 7. Vite plug-in system (from getting started to being able to write) ​

The plug-in follows the Rollup specification + Vite exclusive Hook.

The simplest plug-in ​

ts
export default function MyPlugin() {
  return {
    name: "my-plugin",
    transform(code, id) {
      if (id.endsWith('.js')) {
        return code.replace('hello', 'hi')
      }
    }
  }
}

Plug-in capabilities include: ​

  • transform (compiled code)
  • load (load file)
  • resolveId (custom path)
  • handleHotUpdate(HMR)
  • configureServer (middleware)

Vite can write:

  • Automatic import plugin
  • Mock service plug-in
  • Single file component loader
  • Custom backend proxy

🧩 8. Vite + various frameworks ​

Vue ​

ts
plugins: [vue()]

React (SWC supported) ​

ts
plugins: [react()]

TypeScript ​

TS is supported with zero configuration.

JSX ​

Automatic conversion, no additional configuration required.

🧪 9. Common practical scenarios ​

① Multi-page application ​

ts
build: {
  rollupOptions: {
    input: {
      main: 'index.html',
      admin: 'admin.html'
    }
  }
}

②Mock data ​

Plug-in + middleware implementation.

③ Large-scale project unpacking and optimization ​

Use manualChunks or dynamic import().

🚀 10. Performance optimization ​

development environment ​

  • Disable redundant plugins
  • Pre-build large dependencies (optimizeDeps)
ts
optimizeDeps: {
  include: ['lodash-es']
}

production environment ​

  • gzip/brotli compression
  • Multi-core packaging (using esbuild)
  • Precise subcontracting (manualChunks)
  • CDN acceleration

🧠 11. After mastery: Vite source code learning route ​

To be truly "mastery", you need to understand Vite's source code structure (very clean and easy to read).

Recommended reading order:

1. CLI startup process ​

packages/vite/src/node/cli.ts

2. Development Server Core ​

packages/vite/src/node/server/index.ts

3. Module parsing and dependency pre-building ​

optimizer/ directory

4. HMR implementation ​

server/hmr.ts

5. Plug-in mechanism ​

plugins/ directory pluginContainer.ts

6. Rollup build integration ​

build.ts

Once you understand these, you have truly achieved Vite “mastery”.