适用人群:前端/全栈开发者
难度:低
预计学习时间:3-5小时
Vercel 是什么?
Vercel 是前端部署平台,也是 Next.js 的创建者。支持一键部署前端项目,提供全球CDN、自动HTTPS、预览部署、Serverless Functions等能力。
| 特性 | 说明 |
|---|---|
| 零配置部署 | Git push 自动部署 |
| 全球CDN | 边缘节点加速 |
| 预览部署 | 每个PR自动创建预览URL |
| Serverless | API Routes / Edge Functions |
| 分析 | 性能监控和访客统计 |
支持的框架
| 框架 | 配置 | 特殊支持 |
|---|---|---|
| Next.js | 自动识别 | ISR/SSR/Edge |
| Vite/React | 自动识别 | SPA |
| Astro | 自动识别 | SSG |
| Nuxt | 自动识别 | SSR/SSG |
| SvelteKit | 自动识别 | SSR |
| Hugo | 需要配置 | SSG |
| 纯HTML | 自动识别 | 静态 |
部署步骤
# 方式1:Git集成(推荐)
1. 代码推送到 GitHub/GitLab/Bitbucket
2. 登录 vercel.com
3. 点击 "New Project"
4. 选择仓库,点击 "Deploy"
5. 等待30秒,完成!
# 方式2:Vercel CLI
npm i -g vercel
vercel login
vercel # 部署到预览环境
vercel --prod # 部署到生产环境
vercel env add # 添加环境变量
Serverless Functions
// app/api/hello/route.ts (Next.js App Router)
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ message: 'Hello from Vercel!' })
}
export async function POST(request: Request) {
const body = await request.json()
return NextResponse.json({ received: body })
}
// api/user.ts (传统方式)
import type { VercelRequest, VercelResponse } from '@vercel/node'
export default function handler(req: VercelRequest, res: VercelResponse) {
res.status(200).json({ name: 'John Doe' })
}
// Edge Function
// app/api/edge/route.ts
export const runtime = 'edge'
export async function GET(request: Request) {
return new Response('Hello from Edge!')
}
环境变量
# 在Vercel Dashboard设置
# Settings → Environment Variables
# 或使用CLI
vercel env add DATABASE_URL
# 选择环境:Production / Preview / Development
# 在代码中使用
const dbUrl = process.env.DATABASE_URL
# .env.local 用于本地开发
DATABASE_URL=postgresql://...
NEXT_PUBLIC_API_URL=https://api.example.com
自定义域名
步骤:
1. Settings → Domains
2. 输入你的域名
3. 配置DNS:
- A记录:76.76.21.21
- 或CNAME记录:cname.vercel-dns.com
4. SSL证书自动签发
5. 完成!
免费套餐限制
| 项目 | 免费 | Pro($20/月) |
|---|---|---|
| 带宽 | 100GB/月 | 1TB/月 |
| 构建时间 | 6000分钟/月 | 24000分钟/月 |
| Serverless | 100GB-hours | 1000GB-hours |
| 团队成员 | 1人 | 无限 |
| 域名 | 50个 | 无限 |
| 预览部署 | 无限 | 无限 |
最佳实践
1. 使用 monorepo 管理多个项目
2. 利用预览部署进行PR Review
3. 使用环境变量管理配置
4. 开启Web Analytics监控
5. 使用ISR减少构建次数
6. 配置Edge Middleware做A/B测试
7. 使用Vercel KV/Postgres作为数据库