# 插件实现自动部署

# 🎯 目标

我们希望通过简单的命令:

npm run deploy

就能自动:

  • 构建项目(生成 dist/ 文件夹)
  • dist/ 推送到 GitHub 的 gh-pages 分支
  • 自动更新你托管在 GitHub Pages 的站点内容

# ✅ 步骤详解(以 Vue + Vite 项目为例)

# ① 安装 gh-pages 插件

在项目根目录执行:

npm install --save-dev gh-pages

这个插件就是用来把 dist/ 目录推送到 gh-pages 分支的。

# ② 配置 vite.config.js

添加 base 配置项(必须!否则 GitHub Pages 路径不对):

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  base: '/你的仓库名/', // 注意前后都有斜杠
})

例如你的仓库是 https://github.com/lys123/vue-demo,那么就写:

base: '/vue-demo/'

# ③ 修改 package.json 脚本

{
  "scripts": {
    "build": "vite build",
    "predeploy": "npm run build",    // 自动在部署前构建
    "deploy": "gh-pages -d dist"     // 推送 dist 目录到 gh-pages 分支
  }
}

predeploy 是 Node 的生命周期钩子,会在你运行 npm run deploy 时自动先运行 npm run build

# ④ 初始化 Git 并推送主分支(如果还没做)

git init
git add .
git commit -m "init"
git branch -M main
git remote add origin https://github.com/你的用户名/你的仓库名.git
git push -u origin main

# ⑤ 执行部署命令

npm run deploy

控制台会显示它将 dist/ 推送到了 gh-pages 分支。

# ⑥ 在 GitHub 上启用 Pages

  1. 打开你的 GitHub 仓库
  2. 进入 SettingsPages
  3. Source 中选择:gh-pages 分支 → / (root)
  4. 保存后,GitHub 会生成访问链接,如:
https://你的用户名.github.io/你的仓库名/

# ✅ 总结一张图(流程)

npm run deploy
   ↓
npm run build(自动)
   ↓
vite 构建出 dist/
   ↓
gh-pages 把 dist/ 推送到 gh-pages 分支
   ↓
GitHub Pages 使用 gh-pages 分支作为网站源
   ↓
网站上线 🎉

# 🔁 后续更新内容怎么办?

你只需要改完代码后再次执行:

npm run deploy

即可自动部署最新版网站。

Last Updated: 7/12/2025, 9:03:23 AM