部署指南
完成应用开发后,你需要将其部署到生产环境。本章介绍如何将 Vite 应用部署到各种主流平台。
基本前提
以下部署指南基于以下假设:
- 你使用默认的构建输出位置(
dist),如果使用build.outDir更改了位置,请相应调整 - 你已设置以下 npm 脚本:
{
"scripts": {
"build": "vite build",
"preview": "vite preview"
}
}
重要提示:vite preview 命令用于本地预览构建结果,不适合作为生产服务器使用。
构建应用
运行构建命令:
npm run build
默认情况下,构建输出会放在 dist 目录。你可以将这个目录部署到任何静态文件托管平台。
本地预览
构建完成后,可以在本地预览:
npm run preview
这会启动一个本地静态服务器,从 dist 目录提供文件,默认地址为 http://localhost:4173。
指定端口预览:
{
"scripts": {
"preview": "vite preview --port 8080"
}
}
GitHub Pages
GitHub Pages 是 GitHub 提供的免费静态站点托管服务,非常适合部署个人项目或文档站点。
配置基础路径
在 vite.config.js 中设置正确的 base:
// 部署到 https://<USERNAME>.github.io/
export default defineConfig({
base: '/',
})
// 部署到 https://<USERNAME>.github.io/<REPO>/
export default defineConfig({
base: '/<REPO>/',
})
为什么要设置 base?
当应用部署在子路径时(如 https://username.github.io/my-app/),所有静态资源的 URL 都需要包含这个子路径。设置 base 后,Vite 会自动处理所有资源路径:
- JavaScript 文件:
/my-app/assets/index.js - CSS 文件:
/my-app/assets/index.css - 图片等资源:
/my-app/assets/logo.png
配置 GitHub Actions
GitHub Pages 现在推荐使用 GitHub Actions 进行部署。在项目中创建 .github/workflows/deploy.yml:
# 将静态内容部署到 GitHub Pages 的工作流
name: Deploy static content to Pages
on:
# 在推送到 main 分支时触发
push:
branches: ['main']
# 允许手动触发
workflow_dispatch:
# 设置 GITHUB_TOKEN 的权限以允许部署到 GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# 只允许一个并发部署
concurrency:
group: 'pages'
cancel-in-progress: true
jobs:
# 单个部署作业
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Set up Node
uses: actions/setup-node@v6
with:
node-version: lts/*
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v4
with:
# 上传 dist 目录
path: './dist'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
启用 GitHub Pages
- 进入仓库的 Settings → Pages
- 在 Build and deployment 下,打开 Source 下拉菜单
- 选择 GitHub Actions
- 推送代码到 main 分支,GitHub 会自动部署
处理 SPA 路由
如果你的应用是单页应用(SPA)并使用了前端路由(如 Vue Router、React Router),需要处理页面刷新时的 404 问题。
方案一:使用 404.html 重定向
在 public 目录下创建 404.html,内容与 index.html 相同。GitHub Pages 会将不存在的路径重定向到 404.html。
方案二:使用 copy 插件
// vite.config.js
import { defineConfig } from 'vite'
import { resolve } from 'path'
export default defineConfig({
build: {
rollupOptions: {
output: {
// 构建完成后复制 index.html 为 404.html
},
},
},
})
更简单的方式是在构建脚本中添加:
{
"scripts": {
"build": "vite build && cp dist/index.html dist/404.html"
}
}
GitLab Pages
配置基础路径
// 部署到 https://<USERNAME or GROUP>.gitlab.io/
// base 默认为 '/',可以省略
// 部署到 https://<USERNAME or GROUP>.gitlab.io/<REPO>/
export default defineConfig({
base: '/<REPO>/',
})
配置 GitLab CI
在项目根目录创建 .gitlab-ci.yml:
image: node:lts
pages:
stage: deploy
cache:
key:
files:
- package-lock.json
prefix: npm
paths:
- node_modules/
script:
- npm install
- npm run build
- cp -a dist/. public/
artifacts:
paths:
- public
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
GitLab CI 会自动将 public 目录部署到 GitLab Pages。
Netlify
Netlify 是一个流行的静态站点托管平台,提供自动部署、CDN、HTTPS 等功能。
使用 Netlify CLI
# 安装 Netlify CLI
npm install -g netlify-cli
# 创建新站点
ntl init
# 部署到预览 URL
ntl deploy
# 部署到生产环境
ntl deploy --prod
Netlify CLI 会提供一个预览 URL 供你检查。确认无误后,使用 --prod 标志部署到生产环境。
使用 Git 集成
- 将代码推送到 Git 仓库(GitHub、GitLab、BitBucket)
- 在 Netlify 导入项目
- 选择分支、输出目录,设置环境变量
- 点击 Deploy
Netlify 会自动检测 Vite 项目并配置正确的构建设置。
部署完成后:
- 推送到非生产分支的代码会生成预览部署
- 推送到生产分支(通常是
main)的代码会生成生产部署
处理 SPA 路由
Netlify 会自动处理 SPA 路由,但如果遇到问题,可以在 public 目录下创建 _redirects 文件:
/* /index.html 200
这会将所有路径重定向到 index.html,让前端路由接管。
Vercel
Vercel 是一个专门为前端框架优化的部署平台,对 Vite 有原生支持。
使用 Vercel CLI
# 安装 Vercel CLI
npm i -g vercel
# 部署
vercel
Vercel 会自动检测 Vite 项目并应用正确的配置。
使用 Git 集成
- 将代码推送到 Git 仓库
- 在 Vercel 导入项目
- Vercel 会自动检测 Vite 并配置构建设置
- 点击 Deploy
部署完成后,你的应用会获得一个 .vercel.app 域名。
自定义配置
在项目根目录创建 vercel.json:
{
"buildCommand": "npm run build",
"outputDirectory": "dist",
"framework": "vite",
"rewrites": [
{ "source": "/(.*)", "destination": "/index.html" }
]
}
rewrites 配置用于处理 SPA 路由。
Cloudflare Pages
Cloudflare Pages 提供全球 CDN 和边缘计算能力。
使用 Wrangler CLI
# 安装 Wrangler CLI
npm install -g wrangler
# 登录 Cloudflare 账户
wrangler login
# 构建
npm run build
# 部署
npx wrangler pages deploy dist
Wrangler 会提供一个预览 URL。你也可以在 Cloudflare 仪表板中查看项目。
使用 Git 集成
- 将代码推送到 Git 仓库
- 登录 Cloudflare 仪表板,进入 Account Home > Pages
- 选择 Create a new Project 和 Connect Git
- 选择要部署的项目,点击 Begin setup
- 在构建设置中选择对应的框架预设
- 保存并部署
Firebase Hosting
Firebase Hosting 是 Google 提供的静态托管服务。
安装和配置
# 安装 Firebase CLI
npm install -g firebase-tools
# 登录
firebase login
# 初始化项目
firebase init
在初始化过程中选择 Hosting,并设置:
- Public directory:
dist - Single-page app:
Yes
配置文件
firebase.json:
{
"hosting": {
"public": "dist",
"ignore": [],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
.firebaserc:
{
"projects": {
"default": "<YOUR_FIREBASE_ID>"
}
}
部署
npm run build
firebase deploy
Azure Static Web Apps
Azure Static Web Apps 是微软提供的静态站点托管服务。
前提条件
- Azure 账户和订阅
- 代码推送到 GitHub
- VS Code 中安装 Azure Static Web Apps 扩展
部署步骤
- 在 VS Code 中打开 Static Web Apps 扩展
- 登录 Azure 账户
- 点击 '+' 创建新的 Static Web App
- 按向导设置:
- 应用名称
- 框架预设:选择 Vite
- 应用根目录:
/ - 构建输出目录:
dist
向导会自动在仓库中创建 GitHub Actions 配置文件。
Render
Render 是一个现代化的云平台,支持静态站点部署。
部署步骤
- 创建 Render 账户
- 在仪表板中点击 New,选择 Static Site
- 连接 GitHub/GitLab 账户或使用公开仓库
- 配置:
- Build Command:
npm install && npm run build - Publish Directory:
dist
- Build Command:
- 点击 Create Static Site
默认情况下,推送到指定分支的代码会自动触发部署。
Surge
Surge 是一个简单快速的静态站点发布工具。
# 安装 Surge
npm install -g surge
# 构建
npm run build
# 部署
surge dist
部署到自定义域名:
surge dist yourdomain.com
Docker 容器化部署
将 Vite 应用打包为 Docker 容器:
Dockerfile
# 构建阶段
FROM node:lts-alpine as build-stage
WORKDIR /app
# 复制 package.json 和 lock 文件
COPY package*.json ./
# 安装依赖
RUN npm ci
# 复制源代码
COPY . .
# 构建
RUN npm run build
# 生产阶段
FROM nginx:alpine as production-stage
# 复制构建产物到 nginx 目录
COPY --from=build-stage /app/dist /usr/share/nginx/html
# 复制 nginx 配置
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
nginx.conf
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# 处理 SPA 路由
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
构建和运行
# 构建镜像
docker build -t my-vite-app .
# 运行容器
docker run -d -p 80:80 my-vite-app
部署最佳实践
缓存策略
正确配置缓存策略可以显著提升性能:
# HTML 文件 - 不缓存(始终获取最新版本)
Cache-Control: no-cache
# 带 hash 的静态资源 - 长期缓存
Cache-Control: max-age=31536000, immutable
Vite 默认会为静态资源文件名添加 hash,因此可以安全地设置长期缓存。
环境变量
不同部署环境可能需要不同的环境变量:
# Netlify
NETLIFY=true npm run build
# Vercel
VERCEL=true npm run build
# 自定义
VITE_API_URL=https://api.example.com npm run build
自动化部署
使用 CI/CD 实现自动化部署:
# GitHub Actions 示例
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: lts/*
cache: 'npm'
- run: npm ci
- run: npm run build
- name: Deploy to server
uses: appleboy/scp-[email protected]
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.KEY }}
source: "dist"
target: "/var/www/html"
健康检查
部署后添加健康检查:
// 在应用中添加健康检查端点(如果使用 SSR)
app.get('/health', (req, res) => {
res.status(200).send('OK')
})
或者使用静态文件:
<!-- public/health.html -->
OK
回滚策略
保留之前的部署版本,便于快速回滚:
- Netlify:自动保留每次部署,可一键回滚
- Vercel:自动保留预览部署
- 自建服务器:使用版本化目录结构
/var/www/
├── current -> releases/20240101-1
├── releases/
│ ├── 20240101-1/
│ ├── 20240101-2/
│ └── 20240102-1/
└── shared/
写在最后
将 Vite 应用部署到生产环境有多种选择。对于小型项目,GitHub Pages、Netlify、Vercel 等静态托管平台是不错的选择,它们提供免费额度且配置简单。对于企业级应用,可以考虑 Docker 容器化部署或云服务。
部署时注意配置正确的缓存策略:HTML 文件不缓存,带 hash 的静态资源设置长期缓存。如果使用 SPA 路由,记得配置服务器重定向规则。