前端-Vite基础知识

9 阅读6分钟

Vite 基础知识


一、Vite 概述

1.1 什么是 Vite

Vite 是一个由 Vue 作者尤雨溪开发的现代化前端构建工具,提供快速的开发服务器和优化的生产构建。

核心特点:

  • 极速的开发服务器启动
  • 热模块替换(HMR)快速
  • 基于 ES 模块的构建
  • 开箱即用的 TypeScript 支持
  • 丰富的插件生态

1.2 为什么选择 Vite

特性ViteWebpack
开发服务器启动秒级分钟级
HMR 速度极快较慢
构建速度较慢
配置复杂度简单复杂
生态丰富非常丰富

1.3 工作原理

开发模式:

  • 使用浏览器原生 ES 模块
  • 按需编译,无需打包
  • 依赖预构建(使用 esbuild)

生产模式:

  • 使用 Rollup 打包
  • 代码分割和优化
  • 生成优化的静态资源

二、快速开始

2.1 创建项目

# 使用 npm
npm create vite@latest my-project

# 使用 yarn
yarn create vite my-project

# 使用 pnpm
pnpm create vite my-project

# 指定模板
npm create vite@latest my-vue-app -- --template vue
npm create vite@latest my-react-app -- --template react
npm create vite@latest my-vanilla-app -- --template vanilla

2.2 项目结构

my-project/
├── public/              # 静态资源
├── src/                 # 源代码
│   ├── assets/         # 资源文件
│   ├── components/     # 组件
│   ├── App.vue         # 根组件
│   └── main.js         # 入口文件
├── index.html          # HTML 模板
├── vite.config.js      # Vite 配置
├── package.json
└── README.md

2.3 启动项目

# 安装依赖
npm install

# 开发服务器
npm run dev

# 生产构建
npm run build

# 预览生产构建
npm run preview

三、配置文件

3.1 vite.config.js

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

export default defineConfig({
  // 插件
  plugins: [vue()],
  
  // 开发服务器配置
  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  
  // 构建配置
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: true,
    minify: 'terser',
    chunkSizeWarningLimit: 1000
  },
  
  // 路径别名
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  
  // CSS 配置
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  }
})

3.2 环境变量

.env

VITE_API_URL=http://localhost:8080
VITE_APP_TITLE=My App

.env.development

VITE_API_URL=http://localhost:8080

.env.production

VITE_API_URL=https://api.example.com

使用环境变量:

// 必须以 VITE_ 开头
const apiUrl = import.meta.env.VITE_API_URL
const appTitle = import.meta.env.VITE_APP_TITLE

// 环境判断
if (import.meta.env.DEV) {
  console.log('开发环境')
}

if (import.meta.env.PROD) {
  console.log('生产环境')
}

四、插件系统

4.1 官方插件

# Vue
npm install -D @vitejs/plugin-vue
npm install -D @vitejs/plugin-vue-jsx

# React
npm install -D @vitejs/plugin-react

# TypeScript
npm install -D @vitejs/plugin-react

使用插件:

import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

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

4.2 常用插件

# 路径别名
npm install -D vite-plugin-path-alias

# 自动导入
npm install -D unplugin-auto-import
npm install -D unplugin-vue-components

# 压缩
npm install -D vite-plugin-compression

# 图片优化
npm install -D vite-plugin-imagemin

自动导入配置:

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  plugins: [
    AutoImport({
      resolvers: [ElementPlusResolver()],
      imports: ['vue', 'vue-router']
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    })
  ]
})

五、路径别名

5.1 配置别名

import path from 'path'
import { defineConfig } from 'vite'

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

5.2 使用别名

// 导入组件
import HelloWorld from '@/components/HelloWorld.vue'

// 导入工具函数
import { formatDate } from '@utils/date'

// 导入资源
import logo from '@assets/logo.png'

5.3 TypeScript 支持

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"],
      "@utils/*": ["src/utils/*"]
    }
  }
}

六、静态资源处理

6.1 导入资源

// 图片
import logo from './assets/logo.png'
<img src={logo} />

// 使用 URL
const logoUrl = new URL('./assets/logo.png', import.meta.url).href

// CSS 中的资源
.bg {
  background-image: url('./assets/bg.jpg');
}

6.2 公共目录

public/
├── favicon.ico
└── images/
    └── logo.png
<!-- 直接使用,无需导入 -->
<img src="/images/logo.png" />

6.3 资源 URL

// 显式 URL
import logo from './logo.png?url'

// 原始资源
import logo from './logo.png?raw'

// 查询参数
import logo from './logo.png?w=200&h=200'

七、CSS 处理

7.1 CSS 预处理器

# Sass/SCSS
npm install -D sass

# Less
npm install -D less

# Stylus
npm install -D stylus

使用:

<style lang="scss">
$primary-color: #42b983;

.button {
  background: $primary-color;
}
</style>

7.2 CSS 模块

<template>
  <div :class="$style.container">
    <p :class="$style.text">Hello</p>
  </div>
</template>

<style module>
.container {
  padding: 20px;
}
.text {
  color: #333;
}
</style>

7.3 PostCSS

postcss.config.js

module.exports = {
  plugins: {
    autoprefixer: {},
    tailwindcss: {}
  }
}

八、构建优化

8.1 代码分割

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          'vue-vendor': ['vue', 'vue-router'],
          'utils': ['./src/utils/index.js']
        }
      }
    }
  }
})

8.2 压缩配置

export default defineConfig({
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  }
})

8.3 构建分析

# 安装插件
npm install -D rollup-plugin-visualizer

# 配置
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig({
  plugins: [
    visualizer({
      open: true,
      gzipSize: true,
      brotliSize: true
    })
  ]
})

九、开发服务器

9.1 服务器配置

export default defineConfig({
  server: {
    host: '0.0.0.0',        // 监听所有地址
    port: 3000,             // 端口
    open: true,             // 自动打开浏览器
    cors: true,             // 启用 CORS
    strictPort: false,      // 端口被占用时尝试下一个
    https: false,           // 启用 HTTPS
    
    // 代理配置
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

9.2 HMR 配置

export default defineConfig({
  server: {
    hmr: {
      overlay: true  // 显示错误覆盖层
    }
  }
})

十、生产构建

10.1 构建配置

export default defineConfig({
  build: {
    outDir: 'dist',                    // 输出目录
    assetsDir: 'assets',               // 静态资源目录
    sourcemap: true,                    // 生成 source map
    minify: 'esbuild',                 // 压缩工具
    target: 'es2015',                  // 构建目标
    cssCodeSplit: true,                // CSS 代码分割
    chunkSizeWarningLimit: 1000,       // chunk 大小警告限制
    
    // Rollup 选项
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'index.html')
      },
      output: {
        entryFileNames: 'assets/[name].[hash].js',
        chunkFileNames: 'assets/[name].[hash].js',
        assetFileNames: 'assets/[name].[hash].[ext]'
      }
    }
  }
})

10.2 多页面应用

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'index.html'),
        admin: path.resolve(__dirname, 'admin.html')
      }
    }
  }
})

十一、常用插件

11.1 插件列表

插件说明
@vitejs/plugin-vueVue 支持
@vitejs/plugin-reactReact 支持
vite-plugin-eslintESLint 集成
vite-plugin-stylelintStylelint 集成
unplugin-auto-import自动导入
unplugin-vue-components组件自动导入
vite-plugin-compressionGzip 压缩
vite-plugin-pwaPWA 支持

11.2 插件示例

ESLint 插件:

import eslint from 'vite-plugin-eslint'

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

PWA 插件:

import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg}']
      }
    })
  ]
})

十二、性能优化

12.1 依赖预构建

export default defineConfig({
  optimizeDeps: {
    include: ['vue', 'vue-router'],
    exclude: ['some-big-dependency']
  }
})

12.2 构建优化

export default defineConfig({
  build: {
    // 启用 CSS 代码分割
    cssCodeSplit: true,
    
    // 启用压缩
    minify: 'terser',
    
    // 启用 source map(生产环境可关闭)
    sourcemap: false,
    
    // 代码分割
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor'
          }
        }
      }
    }
  }
})

12.3 图片优化

import viteImagemin from 'vite-plugin-imagemin'

export default defineConfig({
  plugins: [
    viteImagemin({
      gifsicle: { optimizationLevel: 7 },
      optipng: { optimizationLevel: 7 },
      svgo: { plugins: [{ removeViewBox: false }] }
    })
  ]
})

十三、常见问题

13.1 路径别名不生效

问题: 配置了路径别名但导入时报错

解决方案:

  1. 检查 vite.config.js 配置
  2. 检查 tsconfig.json 的 paths 配置
  3. 重启开发服务器

13.2 环境变量未生效

问题: 环境变量读取不到

解决方案:

  • 确保变量名以 VITE_ 开头
  • 使用 import.meta.env.VITE_XXX 访问
  • 重启开发服务器

13.3 构建后资源路径错误

问题: 构建后资源路径 404

解决方案:

export default defineConfig({
  base: '/my-app/',  // 设置基础路径
  build: {
    assetsDir: 'assets'
  }
})

十四、最佳实践

14.1 项目结构

src/
├── assets/         # 静态资源
├── components/     # 组件
├── views/          # 页面
├── router/         # 路由
├── store/          # 状态管理
├── utils/          # 工具函数
├── api/            # API 接口
├── styles/         # 样式
└── main.js         # 入口

14.2 配置管理

// ✅ 使用环境变量管理配置
// ✅ 区分开发和生产配置
// ✅ 使用 TypeScript 类型定义

14.3 性能优化

// ✅ 合理使用代码分割
// ✅ 优化依赖预构建
// ✅ 压缩和优化资源

十五、推荐资源

官方文档:

学习资源:

  • Vite 源码解析
  • Vite 插件开发指南

十六、总结

Vite 核心要点:

极速开发 + 快速 HMR + 优化构建 + 丰富插件 = 现代化构建工具

核心心法:

Vite 让前端开发更快、更简单。 掌握配置和插件是 Vite 开发的关键。


📝 文档信息

  • 作者: 阿鑫
  • 更新日期: 2026.1