前端自动化部署最佳实践
传统手动部署的局限性
手动上传文件到服务器效率低下,容易出错。典型的错误流程包括构建、压缩、SCP 上传、SSH 登录、解压及清理,耗时且繁琐。
# 反面教材:手动部署
npm run build
zip -r build.zip build
scp build.zip user@server:/var/www/html
ssh user@server
unzip build.zip
mv build/* /var/www/html
rm -rf build build.zip
推荐方案
1. CI/CD 流水线
使用 GitHub Actions 实现自动化构建与部署。
name: Deploy
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16'
- run: npm install
- run: npm run build
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build
2. Docker 部署
利用 Docker 容器化技术统一环境。
FROM node:16-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
version: '3'
services:
frontend:
build: .
ports:
- "80:80"
restart: always
3. 环境配置
通过环境变量区分不同环境。
// .env
NODE_ENV=production
REACT_APP_API_URL=https://api.example.com
REACT_APP_WEB_URL=https://example.com
// src/api.js
const API_URL = process.env.REACT_APP_API_URL;
export async function fetchData() {
const response = await fetch(`${API_URL}/data`);
return response.json();
}
4. 缓存策略
配置 Nginx 静态资源缓存以提升性能。
server {
listen 80;
server_name example.com;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
location /api {
proxy_pass https://api.example.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

