当前位置: 首页 > article >正文

Vite入门指南

一、什么是Vite?

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

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

二、环境准备

确保已安装:

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

三、创建第一个项目

1. 初始化项目

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. 启动开发服务器

cd my-vite-app
npm install
npm run dev

访问 http://localhost:5173

四、核心功能实践

1. 模块热替换(HMR)

修改 src/App.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

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

在组件中使用:

import styles from './Button.module.css'

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

3. 静态资源处理

// 直接引入图片
import logo from './assets/react.svg'

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

五、Vite配置详解

修改 vite.config.ts

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插件:

npm install @vitejs/plugin-react -D

配置插件:

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

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

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

npm install vite-plugin-svgr -D

配置:

import svgr from 'vite-plugin-svgr'

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

使用SVG组件:

import { ReactComponent as Logo } from './logo.svg'

function App() {
  return <Logo />
}

七、生产构建

npm run build

生成优化后的静态文件:

dist/
├── static/
│   ├── js/
│   ├── css/
│   └── assets/
└── index.html

八、环境变量

1. 创建环境文件

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

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

VITE_API_URL=https://api.example.com

3. 使用变量

console.log(import.meta.env.VITE_API_URL)

九、与Webpack的主要差异

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

十、完整示例代码

查看GitHub仓库:

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插件实现服务端渲染

http://www.kler.cn/a/549455.html

相关文章:

  • github用户名密码登陆失效了
  • Mac上搭建宝塔环境并部署PHP项目
  • Ubuntu 连接 air pods
  • ios中常见的设计原则和设计模式
  • ARINC 429详解
  • CSS Grid 网格布局,以及 Flexbox 弹性盒布局模型,它们的适用场景是什么?
  • VS Code User和System版区别【推荐使用System版本】and VSCode+Keil协同开发之Keil Assistant
  • 【ISO 14229-1:2023 UDS诊断(会话控制0x10服务)测试用例CAPL代码全解析③】
  • ffmpeg-cli-wrapper操作ffmpeg的工具
  • Anaconda +Jupyter Notebook安装(2025最新版)
  • 问卷数据分析|SPSS实操之量表描述性统计
  • 服务器硬件知识--------linux系统初识and安装
  • 探索Zephyr在汽车领域的应用潜力与挑战
  • 【LLM】13:大模型算法面试题库
  • kubectl exec 实现的原理
  • 力扣 470. 用 Rand7() 实现 Rand10() 拒绝采样 等概率随机数生成
  • SOCKET建立简单的tcp服务端与客户端通信
  • 【Elasticsearch】match查询
  • Matlab实现POA-BP鹈鹕算法优化BP神经网络多输入多输出预测
  • 简单几个步骤完成 Oracle 到金仓数据库(KingbaseES)的迁移目标