跳到主要内容

Vue 构建工具

Vue 项目可以使用多种构建工具,最常用的是 Vite 和 Vue CLI。本章将详细介绍这两种工具的使用方法。

Vite

什么是 Vite?

Vite 是新一代前端构建工具,具有以下特点:

  • 极速的开发体验:基于 ES Module,开发时无需打包
  • 即时的模块热更新(HMR):修改代码后立即反映
  • 内置 TypeScript 支持
  • 生产环境 Rollup 优化
┌─────────────────────────────────────────────────────────┐
│ Vite 工作原理 │
├─────────────────────────────────────────────────────────┤
│ │
│ 开发环境: │
│ ┌─────────────┐ │
│ │ Browser │ 直接请求 .vue 文件 │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Vite │───▶│ Transform │ Vue ──▶ ES Module │
│ │ Server │ └─────────────┘ │
│ └─────────────┘ │
│ │
│ 生产环境: │
│ ┌─────────────┐ │
│ │ Rollup │ 打包优化 │
│ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────┘

创建项目

# 交互式创建
npm create vue@latest

# 指定模板
npm create vue@latest my-app -- --typescript --vue-router --pinia

常用命令

npm run dev      # 启动开发服务器
npm run build # 构建生产版本
npm run preview # 预览生产版本
npm run lint # 代码检查

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,
host: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
},

build: {
outDir: 'dist',
assetsDir: 'assets',
sourcemap: false
}
})

Vue CLI

什么是 Vue CLI?

Vue CLI 是 Vue 官方提供的脚手架工具,虽然现在推荐使用 Vite,但 Vue CLI 仍有其价值。

安装和使用

# 全局安装
npm install -g @vue/cli

# 创建项目
vue create my-vue-app

# 启动开发服务器
cd my-vue-app
npm run serve

常用命令

vue create project-name    # 创建项目
vue add vuetify # 添加 Vuetify
vue add router # 添加 Vue Router
vue add pinia # 添加 Pinia
vue build # 构建生产版本
vue ui # 打开 GUI

项目结构

Vite 项目结构

my-vue-app/
├── public/ # 静态资源(不会被处理)
│ └── favicon.ico
├── src/ # 源代码
│ ├── assets/ # 资源文件(会被处理)
│ │ └── logo.png
│ ├── components/ # 组件
│ │ └── HelloWorld.vue
│ ├── composables/ # 组合式函数
│ │ └── useCounter.js
│ ├── router/ # 路由配置
│ │ └── index.js
│ ├── stores/ # Pinia stores
│ │ └── counter.js
│ ├── views/ # 页面视图
│ │ └── Home.vue
│ ├── App.vue # 根组件
│ └── main.js # 入口文件
├── index.html # HTML 入口
├── package.json
├── vite.config.js # Vite 配置
└── README.md

入口文件

// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import App from './App.vue'
import './assets/main.css'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(router)

app.mount('#app')

环境变量

.env 文件

# .env - 所有环境
VUE_APP_TITLE=My App
VUE_APP_API_URL=https://api.example.com
# .env.development - 开发环境
VITE_API_URL=http://localhost:8080
# .env.production - 生产环境
VITE_API_URL=https://api.example.com

使用环境变量

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

// Vue CLI
console.log(process.env.VUE_APP_API_URL)
<template>
<h1>{{ appTitle }}</h1>
</template>

<script setup>
const appTitle = import.meta.env.VITE_APP_TITLE || '默认标题'
</script>

CSS 预处理器

安装

# Sass
npm install -D sass sass-loader

# Less
npm install -D less less-loader

# Stylus
npm install -D stylus stylus-loader

使用

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

.container {
background: $primary;
}
</style>

CSS Modules

<style module>
/* 自动转换为 $style.container */
.container {
color: red;
}

.title {
font-size: 20px;
}
</style>

<template>
<div :class="$style.container">
<h1 :class="$style.title">标题</h1>
</div>
</template>

构建优化

代码分割

// 路由懒加载
const routes = [
{
path: '/',
component: () => import('./views/Home.vue')
},
{
path: '/about',
component: () => import('./views/About.vue')
}
]
// 组件懒加载
const AsyncModal = defineAsyncComponent(() =>
import('./components/Modal.vue')
)

预加载

<!-- index.html -->
<link rel="preload" href="/src/assets/main.css" as="style">
<link rel="modulepreload" href="/src/main.js">

压缩

// vite.config.js
import { defineConfig } from 'vite'
import viteCompression from 'vite-plugin-compression'

export default defineConfig({
plugins: [
vue(),
viteCompression({
algorithm: 'gzip',
ext: '.gz'
})
]
})

部署

构建

npm run build

部署配置

// vue.config.js (Vue CLI)
module.exports = {
publicPath: '/my-app/',
outputDir: 'dist',
assetsDir: 'static',
productionSourceMap: false
}
// vite.config.js
export default defineConfig({
base: '/my-app/',
build: {
outDir: 'dist'
}
})

开发技巧

热更新配置

// vite.config.js
export default defineConfig({
server: {
port: 3000,
open: true, // 自动打开浏览器
cors: true, // 允许跨域
hmr: {
overlay: true // 显示错误遮罩
}
}
})

代理配置

// vite.config.js
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})

小结

本章我们详细学习了 Vue 构建工具的完整内容:

  1. Vite:新一代构建工具,快速 HMR
  2. Vue CLI:传统脚手架工具
  3. 项目结构:标准目录结构
  4. 环境变量:开发和生产环境配置
  5. CSS 预处理器:Sass、Less、Stylus
  6. 构建优化:代码分割、压缩、预加载
  7. 部署:构建和部署配置

练习

  1. 配置 Vite 代理解决跨域问题
  2. 使用环境变量区分开发和生产 API
  3. 配置 CSS Modules

准备好进入速查表章节了吗?