Vite 中文教程

1. 什么是 Vite?

Vite(发音为 "veet")是一个现代化的前端构建工具,由 Vue.js 的作者尤雨溪创建。它的设计理念是"快速的开发服务器和优化的构建",通过利用浏览器的 ES 模块支持和原生 ESM 导入,提供了极速的开发体验。

1.1 Vite 的核心优势

  • 极速开发服务器:利用浏览器的原生 ESM 支持,实现按需编译,启动速度极快。
  • **热模块替换 (HMR)**:即时的模块热更新,无需刷新页面即可看到更改。
  • 优化的构建:使用 Rollup 进行生产构建,生成高度优化的静态资源。
  • 智能代码拆分:自动进行代码拆分,减少初始加载体积。
  • 类型支持:内置 TypeScript 支持,无需额外配置。
  • CSS 处理:内置 CSS 预处理器支持,包括 CSS Modules、PostCSS 等。
  • 插件系统:通过插件扩展核心功能,支持各种框架和工具。
  • 与框架无关:支持多种前端框架,包括 Vue、React、Svelte 等。
  • 生态系统:丰富的插件和预设,简化开发流程。

2. 安装和初始化

2.1 使用 npm 创建项目

Vite 提供了多种模板,可以根据需要选择:

# 使用 npm
npm create vite@latest my-vite-app -- --template vue

# 使用 yarn
yarn create vite my-vite-app --template vue

# 使用 pnpm
pnpm create vite my-vite-app --template vue

2.2 支持的模板

Vite 支持以下官方模板:

  • vanilla:纯 JavaScript 项目
  • vanilla-ts:TypeScript 项目
  • vue:Vue 3 项目
  • vue-ts:Vue 3 + TypeScript 项目
  • react:React 项目
  • react-ts:React + TypeScript 项目
  • react-swc:React + SWC 编译器
  • react-ts-swc:React + TypeScript + SWC 编译器
  • svelte:Svelte 项目
  • svelte-ts:Svelte + TypeScript 项目

2.3 手动安装

如果你想手动安装 Vite,可以按照以下步骤:

# 创建项目目录
mkdir my-vite-app
cd my-vite-app

# 初始化 package.json
npm init -y

# 安装 Vite
npm install vite

# 添加脚本
# 在 package.json 中添加:
# "scripts": {
#   "dev": "vite",
#   "build": "vite build",
#   "preview": "vite preview"
# }

# 创建基本文件
# index.html
# src/main.js
# src/style.css

2.4 验证安装

# 启动开发服务器
npm run dev

# 访问 http://localhost:5173

# 构建生产版本
npm run build

# 预览生产构建
npm run preview

# 访问 http://localhost:4173

3. 基本配置

Vite 使用 vite.config.jsvite.config.ts 文件进行配置:

3.1 基本配置

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  // 项目根目录
  root: process.cwd(),
  // 输出目录
  build: {
    outDir: 'dist'
  },
  // 开发服务器配置
  server: {
    port: 5173,
    open: true
  }
})

3.2 常用配置选项

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

export default defineConfig({
  // 插件
  plugins: [vue()],
  // 解析配置
  resolve: {
    // 别名
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  // 服务器配置
  server: {
    port: 3000,
    open: true,
    // 代理配置
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true
      }
    }
  },
  // 构建配置
  build: {
    outDir: 'dist',
    // 资源输出目录
    assetsDir: 'assets',
    // 生成 sourcemap
    sourcemap: false,
    // 最小化
    minify: 'terser',
    //  chunk 大小警告阈值
    chunkSizeWarningLimit: 1000
  },
  // CSS 配置
  css: {
    // 预处理器选项
    preprocessorOptions: {
      scss: {
        additionalData: `@import "./src/styles/variables.scss";`
      }
    }
  }
})

4. 核心功能

4.1 开发服务器

Vite 的开发服务器是其最强大的特性之一,它利用浏览器的原生 ESM 支持,实现了极速的启动速度和热模块替换。

4.1.1 基本使用

# 启动开发服务器
npm run dev

# 指定端口
npm run dev -- --port 3000

# 禁止自动打开浏览器
npm run dev -- --open false

4.1.2 服务器配置

// vite.config.js
export default defineConfig({
  server: {
    // 端口
    port: 3000,
    // 主机
    host: '0.0.0.0',
    // 自动打开浏览器
    open: true,
    // 热模块替换
    hmr: {
      overlay: true
    },
    // 代理
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

4.2 生产构建

Vite 使用 Rollup 进行生产构建,生成高度优化的静态资源。

4.2.1 基本使用

# 构建生产版本
npm run build

# 构建预览
npm run preview

4.2.2 构建配置

// vite.config.js
export default defineConfig({
  build: {
    // 输出目录
    outDir: 'dist',
    // 资源目录
    assetsDir: 'assets',
    // 生成 sourcemap
    sourcemap: false,
    // 最小化
    minify: 'terser',
    // terser 配置
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    },
    // 代码拆分
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['vue'],
          router: ['vue-router'],
          store: ['pinia']
        }
      }
    }
  }
})

4.3 热模块替换 (HMR)

Vite 的热模块替换功能非常强大,可以即时更新更改,无需刷新页面。

4.3.1 基本原理

Vite 的 HMR 实现基于以下原理:

  1. 开发服务器监听文件变化
  2. 当文件变化时,服务器重新编译该模块
  3. 通过 WebSocket 向浏览器发送更新通知
  4. 浏览器接收更新并替换相应的模块
  5. 保持应用状态不变

4.3.2 自定义 HMR

对于复杂的应用,可能需要自定义 HMR 行为:

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

const app = createApp(App)
app.mount('#app')

// 自定义 HMR 处理
if (import.meta.hot) {
  import.meta.hot.accept('./App.vue', (newApp) => {
    // 替换根组件
    app.unmount()
    app.component('App', newApp.default)
    app.mount('#app')
  })
}

4.4 CSS 处理

Vite 内置了强大的 CSS 处理能力,包括 CSS Modules、预处理器支持等。

4.4.1 基本 CSS

/* src/style.css */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

/* 在 JavaScript 中导入 */
import './style.css'

4.4.2 CSS Modules

/* src/components/Button.module.css */
.button {
  padding: 10px 20px;
  background-color: #0070f3;
  color: white;
  border: none;
  border-radius: 4px;
}

/* 在组件中使用 */
import styles from './Button.module.css'

export default function Button() {
  return <button className={styles.button}>Click me</button>
}

4.4.3 CSS 预处理器

Vite 内置支持 CSS 预处理器,无需额外配置:

# 安装预处理器
npm install -D sass

# 或
npm install -D less

# 或
npm install -D stylus
/* src/styles/variables.scss */
$primary-color: #0070f3;
$secondary-color: #f0f0f0;

/* src/components/Button.scss */
@import '../styles/variables.scss';

.button {
  padding: 10px 20px;
  background-color: $primary-color;
  color: white;
  border: none;
  border-radius: 4px;
}

/* 在组件中导入 */
import './Button.scss'

4.5 静态资源处理

Vite 提供了多种处理静态资源的方式,包括导入、URL 引用等。

4.5.1 导入静态资源

// 导入图像
import logo from './assets/logo.png'

// 在组件中使用
function App() {
  return <img src={logo} alt="Logo" />
}

// 导入 JSON
import data from './data.json'

// 导入 WebWorker
import Worker from './worker?worker'

// 导入 WASM
import init from './module.wasm'

4.5.2 公共目录

Vite 会将 public 目录中的文件直接复制到输出目录的根目录,可以通过绝对路径访问:

public/
├── favicon.ico
└── robots.txt
<!-- 在 HTML 中使用 -->
<link rel="icon" href="/favicon.ico" />

5. 插件系统

Vite 的插件系统是其扩展性的核心,通过插件可以扩展 Vite 的核心功能。

5.1 内置插件

Vite 内置了多种插件,包括:

  • @vitejs/plugin-vue:Vue 3 单文件组件支持
  • @vitejs/plugin-react:React 支持
  • @vitejs/plugin-legacy:生成传统浏览器兼容代码
  • @vitejs/plugin-pwa:PWA 支持

5.2 安装和使用插件

# 安装 Vue 插件
npm install -D @vitejs/plugin-vue

# 安装 React 插件
npm install -D @vitejs/plugin-react

# 安装 PWA 插件
npm install -D @vitejs/plugin-pwa
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    vue(),
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.ico', 'robots.txt'],
      manifest: {
        name: 'My Vite App',
        short_name: 'Vite App',
description: 'A Vite application',
        theme_color: '#0070f3'
      }
    })
  ]
})

5.3 常用插件

以下是一些常用的 Vite 插件:

  • vite-plugin-pwa:PWA 支持
  • vite-plugin-svg-icons:SVG 图标组件
  • vite-plugin-compression:资源压缩
  • vite-plugin-imagemin:图像优化
  • vite-plugin-html:HTML 模板处理
  • vite-plugin-mock:Mock 数据支持
  • vite-plugin-eslint:ESLint 集成
  • vite-plugin-stylelint:Stylelint 集成

6. 与框架集成

6.1 Vue

Vite 是 Vue 3 的官方构建工具,提供了最佳的开发体验:

# 创建 Vue 项目
npm create vite@latest my-vue-app -- --template vue

# 创建 Vue + TypeScript 项目
npm create vite@latest my-vue-app -- --template vue-ts

Vue 插件配置:

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

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

6.2 React

Vite 对 React 提供了很好的支持,包括 JSX 语法、HMR 等:

# 创建 React 项目
npm create vite@latest my-react-app -- --template react

# 创建 React + TypeScript 项目
npm create vite@latest my-react-app -- --template react-ts

# 创建 React + SWC 项目
npm create vite@latest my-react-app -- --template react-swc

React 插件配置:

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

export default defineConfig({
  plugins: [react()]
})

6.3 Svelte

Vite 对 Svelte 也提供了良好的支持:

# 创建 Svelte 项目
npm create vite@latest my-svelte-app -- --template svelte

# 创建 Svelte + TypeScript 项目
npm create vite@latest my-svelte-app -- --template svelte-ts

Svelte 插件配置:

// vite.config.js
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

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

7. 性能优化

7.1 代码拆分

Vite 会自动进行代码拆分,但对于大型应用,可能需要手动优化:

// vite.config.js
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          // 将第三方库拆分为单独的 chunk
          vendor: ['vue', 'vue-router', 'pinia'],
          // 将工具函数拆分为单独的 chunk
          utils: ['lodash', 'axios'],
          // 将 UI 组件拆分为单独的 chunk
          ui: ['ant-design-vue']
        }
      }
    }
  }
})

7.2 延迟加载

对于大型组件或库,可以使用动态导入进行延迟加载:

// 动态导入组件
const HeavyComponent = () => import('./HeavyComponent.vue')

// 条件加载
if (condition) {
  const { default: library } = await import('heavy-library')
  // 使用 library
}

// 路由懒加载(Vue Router)
const routes = [
  {
    path: '/dashboard',
    component: () => import('./views/Dashboard.vue')
  }
]

7.3 图像优化

使用插件优化图像加载:

# 安装图像优化插件
npm install -D vite-plugin-imagemin
// vite.config.js
import { defineConfig } from 'vite'
import viteImagemin from 'vite-plugin-imagemin'

export default defineConfig({
  plugins: [
    viteImagemin({
      gifsicle: {
        optimizationLevel: 7,
        interlaced: false
      },
      optipng: {
        optimizationLevel: 7
      },
      mozjpeg: {
        quality: 80
      },
      pngquant: {
        quality: [0.8, 0.9],
        speed: 4
      },
      svgo: {
        plugins: [
          {
            name: 'removeViewBox'
          },
          {
            name: 'removeEmptyAttrs',
            active: false
          }
        ]
      }
    })
  ]
})

7.4 预加载

使用预加载提示浏览器提前加载关键资源:

<!-- 预加载字体 -->
<link rel="preload" href="/fonts/roboto.woff2" as="font" type="font/woff2" crossorigin>

<!-- 预加载图像 -->
<link rel="preload" href="/images/hero.jpg" as="image">

<!-- 预加载脚本 -->
<link rel="preload" href="/js/vendor.js" as="script">

7.5 缓存策略

配置适当的缓存策略,减少重复请求:

// vite.config.js
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        // 使用内容哈希命名文件
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
      }
    }
  }
})

8. 最佳实践

8.1 目录结构

my-vite-app/
├── public/          # 静态资源(直接复制到输出目录)
├── src/             # 源代码
│   ├── assets/       # 资源文件
│   ├── components/   # 组件
│   ├── views/        # 页面视图
│   ├── router/       # 路由配置
│   ├── store/        # 状态管理
│   ├── services/     # API 服务
│   ├── utils/        # 工具函数
│   ├── styles/       # 全局样式
│   ├── main.js       # 入口文件
│   └── App.vue       # 根组件
├── index.html        # HTML 模板
├── vite.config.js    # Vite 配置
├── package.json      # 项目配置
└── README.md         # 项目说明

8.2 配置管理

对于不同环境,使用不同的配置:

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// 加载环境变量
const env = process.env.NODE_ENV

export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: env === 'production' ? 'https://api.example.com' : 'http://localhost:8080',
        changeOrigin: true
      }
    }
  },
  build: {
    sourcemap: env === 'development'
  }
})

8.3 环境变量

使用 .env 文件管理环境变量:

# .env
VITE_API_BASE_URL=http://localhost:8080/api
VITE_APP_TITLE=My App

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

在代码中使用:

// 访问环境变量
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL
const appTitle = import.meta.env.VITE_APP_TITLE

8.4 部署策略

Vite 生成的静态文件可以部署到任何静态托管服务:

8.4.1 Netlify

  1. 将代码推送到 GitHub、GitLab 或 Bitbucket
  2. 在 Netlify 上导入项目
  3. 配置构建命令:npm run build
  4. 配置发布目录:dist
  5. 部署完成后获得一个 URL

8.4.2 Vercel

  1. 将代码推送到 GitHub、GitLab 或 Bitbucket
  2. 在 Vercel 上导入项目
  3. 配置构建命令:npm run build
  4. 配置发布目录:dist
  5. 部署完成后获得一个 URL

8.4.3 GitHub Pages

  1. 安装 gh-pages 插件:npm install gh-pages
  2. package.json 中添加脚本:&quot;deploy&quot;: &quot;npm run build &amp;&amp; gh-pages -d dist&quot;
  3. 运行部署命令:npm run deploy
  4. 部署到 https://&lt;username&gt;.github.io/&lt;repository-name&gt;

8.5 开发工作流

8.5.1 代码规范

集成 ESLint 和 Prettier,保持代码风格一致:

# 安装依赖
npm install -D eslint prettier eslint-plugin-vue @vue/eslint-config-prettier
// .eslintrc.js
module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    '@vue/prettier'
  ],
  rules: {
    // 自定义规则
  }
}

// .prettierrc
{
  "semi": false,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5"
}

8.5.2 测试

集成测试工具,确保代码质量:

# 安装 Vitest
npm install -D vitest

# 安装 Cypress(端到端测试)
npm install -D cypress
// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom'
  }
})

// package.json
// "scripts": {
//   "test": "vitest",
//   "e2e": "cypress open"
// }

9. 常见问题与解决方案

9.1 模块解析问题

问题:模块找不到或解析失败

解决方案

  • 检查模块路径是否正确
  • 确保依赖已正确安装
  • 配置 resolve.alias 解决路径问题
  • 检查文件扩展名是否正确

9.2 热模块替换不工作

问题:HMR 不更新或更新失败

解决方案

  • 检查浏览器控制台是否有错误
  • 确保代码没有语法错误
  • 检查 vite.config.js 中的 HMR 配置
  • 尝试重启开发服务器

9.3 构建失败

问题vite build 执行失败

解决方案

  • 检查控制台错误信息,定位具体问题
  • 确保所有依赖都已正确安装
  • 检查代码是否有语法错误
  • 检查 vite.config.js 配置是否正确

9.4 生产环境问题

问题:开发环境正常,生产环境出错

解决方案

  • 检查环境变量配置
  • 确保所有依赖都已正确安装
  • 检查构建输出是否正确
  • 使用 npm run preview 本地预览生产构建

9.5 性能问题

问题:应用加载缓慢或运行卡顿

解决方案

  • 使用代码拆分减少初始加载体积
  • 延迟加载大型组件和库
  • 优化图像和资源
  • 使用性能分析工具定位瓶颈
  • 配置适当的缓存策略

10. 总结

Vite 是一个现代化的前端构建工具,它通过利用浏览器的原生 ESM 支持和优化的构建过程,提供了极速的开发体验和高度优化的生产构建。

通过本教程,你应该已经了解了 Vite 的基本概念、核心功能和最佳实践。Vite 的设计理念和技术实现代表了前端构建工具的未来发展方向,它的出现极大地提升了前端开发的效率和体验。

Vite 的优势在于:

  1. 极速开发服务器:利用浏览器的原生 ESM 支持,实现了极速的启动速度。
  2. 热模块替换:即时的模块热更新,无需刷新页面即可看到更改。
  3. 优化的构建:使用 Rollup 进行生产构建,生成高度优化的静态资源。
  4. 与框架无关:支持多种前端框架,包括 Vue、React、Svelte 等。
  5. 丰富的生态系统:通过插件扩展核心功能,支持各种工具和库。

无论是构建小型应用还是大型企业级项目,Vite 都能为你提供出色的开发体验和性能表现。随着 Vite 的不断发展和完善,它已经成为前端开发的首选构建工具之一。

« 上一篇 Eleventy 中文教程 下一篇 » 71. Webpack 教程