还在手动上传 Vue 项目 dist 目录?这五种快捷部署方案速来!

使用Vue开发项目,每次编译后需要手动将dist目录上传到服务器,那有没有更便捷的方法呢?这个问题其实很常见,尤其是在需要频繁部署的时候。常见的解决方案可能包括使用自动化脚本、CI/CD工具,或者利用Git的钩子或平台功能。

方案一:Shell 脚本 + rsync(最快实现)

  1. 创建 deploy.sh 脚本
1
2
3
# deploy.sh
npm run build && \
rsync -avz --delete -e "ssh -p 22" ./dist/ user@yourserver:/path/to/target
  1. package.json 中添加部署脚本
1
2
3
4
// package.json
"scripts": {
"deploy": "sh deploy.sh"
}
  1. 运行 npm run deploy 即可完成构建部署

方案二:GitHub Actions 自动化(推荐团队使用)

  1. 在项目根目录创建 .github/workflows/deploy.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
name: CI/CD Pipeline

on:
push:
branches: [ main ]

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 18

- name: Install dependencies
run: npm ci

- name: Build project
run: npm run build

- name: Deploy to Server
uses: appleboy/scp-action@v0.1.3
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
port: 22
source: "dist/*"
target: "/var/www/your-project"

方案三:Webpack 插件自动上传(适合纯前端项目)

  1. 安装依赖
1
npm install ssh2-sftp-client --save-dev
  1. 修改 vue.config.js 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// vue.config.js
const Client = require('ssh2-sftp-client');

module.exports = {
chainWebpack: (config) => {
config.plugin('deploy').tap(() => [
{
apply: (compiler) => {
compiler.hooks.afterEmit.tapAsync('DeployPlugin', (compilation, callback) => {
const sftp = new Client();

sftp.connect({
host: 'your-server.com',
port: 22,
username: 'deploy-user',
privateKey: require('fs').readFileSync(require('os').homedir() + '/.ssh/id_rsa')
})
.then(() => sftp.uploadDir('dist', '/var/www/html'))
.finally(() => {
sftp.end();
callback();
});
});
}
}
]);
}
}

方案四:Docker 容器化部署(适合微服务架构)

  1. 创建 Dockerfile
1
2
3
4
5
6
7
8
9
10
FROM node:18-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
  1. 创建部署脚本
1
2
3
4
#!/bin/bash
docker build -t vue-app .
docker save vue-app | ssh user@server "docker load"
ssh user@server "docker run -d -p 80:80 --restart always vue-app"

方案五:使用 Serverless 服务(最快上线)

  1. 安装 Vercel CLI
1
npm install -g vercel
  1. 创建 vercel.json
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"version": 2,
"builds": [
{
"src": "dist/**/*",
"use": "@vercel/static"
}
],
"routes": [
{ "handle": "filesystem" },
{ "src": "/.*", "dest": "/index.html" }
]
}
  1. 部署命令
1
npm run build && vercel --prod

安全建议(所有方案通用)

  1. 使用 SSH 密钥认证代替密码
  2. 敏感信息处理
  • 永远不要将凭证提交到代码仓库
  • 使用环境变量(GitHub Secrets / .env 文件)
  • 服务器目录权限设置:
1
2
chown -R www-data:www-data /var/www/html
chmod -R 755 /var/www/html

选择方案优先级建议:

  1. 个人项目 → 方案一
  2. 团队协作 → 方案二
  3. 需要灰度发布 → 方案四
  4. 快速原型 → 方案五
  5. 需要构建时触发 → 方案三

可以根据实际需求组合使用这些方案,例如用 GitHub Actions 触发 Docker 构建部署。