Vite入门指南

一、什么是Vite?

Vite(法语意为"快速")是由Vue作者尤雨溪开发的新型前端构建工具。它基于原生ES模块(ESM)实现,具有以下核心优势:

  • 极速启动:冷启动时间比Webpack快10-100倍
  • 闪电般的热更新:HMR(热模块替换)保持应用状态
  • 开箱即用的支持:TypeScript、JSX、CSS预处理等
  • 灵活的扩展:通过插件支持Rollup生态系统

二、环境准备

确保已安装:

  • Node.js 14.18+ / 16+
  • npm 7+ 或 yarn
bash 复制代码
# 验证安装
node -v
npm -v

三、创建第一个项目

1. 初始化项目

bash 复制代码
npm create vite@latest my-vite-app

选择框架模板(这里以React+TS为例):

复制代码
✔ Select a framework: › React
✔ Select a variant: › TypeScript

2. 项目结构

复制代码
my-vite-app/
├── node_modules/
├── public/
│   └── vite.svg
├── src/
│   ├── assets/
│   ├── App.css
│   ├── App.tsx
│   ├── index.css
│   ├── main.tsx
│   └── vite-env.d.ts
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts

3. 启动开发服务器

bash 复制代码
cd my-vite-app
npm install
npm run dev

访问 http://localhost:5173

四、核心功能实践

1. 模块热替换(HMR)

修改 src/App.tsx

tsx 复制代码
function App() {
  return (
    <div className="App">
      <h1>Hello Vite!</h1>
      <p>Edit and save to see HMR in action</p>
    </div>
  )
}

保存后浏览器立即更新,无需刷新页面

2. CSS处理

创建 src/Button.module.css

css 复制代码
.primary {
  background: #646cff;
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
}

在组件中使用:

tsx 复制代码
import styles from './Button.module.css'

function Button() {
  return <button className={styles.primary}>Click Me</button>
}

3. 静态资源处理

tsx 复制代码
// 直接引入图片
import logo from './assets/react.svg'

function Logo() {
  return <img src={logo} alt="React logo" />
}

五、Vite配置详解

修改 vite.config.ts

typescript 复制代码
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true
  },
  build: {
    outDir: 'dist',
    assetsDir: 'static'
  }
})

六、插件系统

1. 常用插件示例

安装官方React插件:

bash 复制代码
npm install @vitejs/plugin-react -D

配置插件:

typescript 复制代码
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: ['babel-plugin-styled-components']
      }
    })
  ]
})

2. 社区插件示例(以SVG转换为例)

bash 复制代码
npm install vite-plugin-svgr -D

配置:

typescript 复制代码
import svgr from 'vite-plugin-svgr'

export default defineConfig({
  plugins: [
    svgr({
      svgrOptions: {
        icon: true
      }
    })
  ]
})

使用SVG组件:

tsx 复制代码
import { ReactComponent as Logo } from './logo.svg'

function App() {
  return <Logo />
}

七、生产构建

bash 复制代码
npm run build

生成优化后的静态文件:

复制代码
dist/
├── static/
│   ├── js/
│   ├── css/
│   └── assets/
└── index.html

八、环境变量

1. 创建环境文件

复制代码
.env                # 所有情况
.env.local          # 本地覆盖,git忽略
.env.development    # 开发环境
.env.production     # 生产环境

2. 定义变量(前缀必须为VITE_)

env 复制代码
VITE_API_URL=https://api.example.com

3. 使用变量

tsx 复制代码
console.log(import.meta.env.VITE_API_URL)

九、与Webpack的主要差异

特性 Vite Webpack
启动时间 毫秒级 随着项目增长变慢
构建方式 ESM原生模块 Bundle打包
HMR速度 保持状态快速更新 需要重建模块
配置复杂度 简单 相对复杂
生态 快速成长 成熟

十、完整示例代码

查看GitHub仓库:

bash 复制代码
git clone https://github.com/vitejs/vite-template-react.git

十一、最佳实践

  1. 按需加载:使用动态import实现代码分割
  2. 缓存策略:配置合理的hash文件名
  3. 性能优化 :使用 vite-plugin-compression 进行Gzip压缩
  4. 类型安全:充分利用TypeScript类型检查
  5. SSR支持:结合vite-ssr插件实现服务端渲染
相关推荐
崔庆才丨静觅11 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606112 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了12 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅12 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅12 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅13 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment13 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅13 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊13 小时前
jwt介绍
前端
爱敲代码的小鱼13 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax