前端部署:别让你的应用在上线后掉链子
前端部署:别让你的应用在上线后掉链子
毒舌时刻
这部署流程写得跟绕口令似的,谁能记得住?
各位前端同行,咱们今天聊聊前端部署。别告诉我你还在手动上传文件到服务器,那感觉就像在石器时代用石头砸坚果——能用,但效率低得可怜。
为什么你需要自动化部署
最近看到一个项目,部署时需要手动复制文件到服务器,每次部署都要花上几个小时。我就想问:你是在做部署还是在做体力活?
反面教材
# 反面教材:手动部署 # 1. 构建项目 npm run build # 2. 压缩文件 zip -r build.zip build # 3. 上传到服务器 scp build.zip user@server:/var/www/html # 4. 登录服务器 ssh user@server # 5. 解压文件 unzip build.zip # 6. 移动文件 mv build/* /var/www/html # 7. 清理文件 rm -rf build build.zip 毒舌点评:这部署流程,就像在徒步穿越沙漠,累得要命还慢。
正确姿势
1. CI/CD 流水线
# 正确姿势:GitHub Actions # .github/workflows/deploy.yml 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 部署 # Dockerfile 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;"] # docker-compose.yml 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.conf 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"; } # API 代理 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; } } 毒舌点评:这才叫前端部署,自动化流程,高效可靠,再也不用担心部署出错了。