純 Git 實現(xiàn)前端 CI/CD
作者:楊成功
來源:SegmentFault 思否社區(qū)
最近要高效的把前端 react 項目部署到私有服務(wù)器上,研究了好幾種持續(xù)部署方案,這里簡單描述一下。
總的部署思路分兩種:
編譯后的文件部署 源碼部署
npm run build打包,生成 build 文件夾,然后將 build 文件夾傳到服務(wù)器,再用 Nginx 配置一個靜態(tài)解析即可。$?npm?install?&&?npm?run?build
服務(wù)端
node?git?nginx,開始動手。創(chuàng)建裸倉庫
.git?文件夾$?cd?/opt
$?git?init?--bare?react-test.git
/opt/react-test.git,記住這里后面會用到。hook?文件夾。這個文件夾可不得了,是放 Git “鉤子” 的地方。添加 push 鉤子
post-receive?文件,這個鉤子文件會在代碼 push 到這個裸倉庫后執(zhí)行,這里是本文最重要的重點(diǎn)。$?cd?/opt/react-test.git/hook
$?vim?post-receive
#!/bin/bash
echo?'server:?received?code?push...'
cd?/home/react-test
echo?'server:?checkout?latest?code?from?git...'
git?--git-dir=/opt/react-test.git?--work-tree=/home/react-test?checkout?-f?release
echo?'server:?running?npm?install...'
npm?install?\
&&?echo?'server:?buildding...'?\
&&?npm?run?build?\
&&?echo?'server:?done...'
git?--git-dir=/opt/react-test.git?--work-tree=/home/react-test?checkout?-f?release
git init?初始化 git 倉庫。執(zhí)行的 add,commit 等操作,默認(rèn)就是與這個倉庫交換文件。項目目錄?和?git 倉庫。項目目錄就是 package.json 文件所在的目錄,我們的代碼放在這里。git 倉庫是項目目錄下的?.git?文件夾,它是個隱藏目錄,在?npm init?時自動生成。--git-dir?參數(shù)就允許你指定一個其他的 git 倉庫。/home/react-test?下修改的文件添加到暫存區(qū):#?默認(rèn)加到?/home/react-test/.git
$?git?add?.
#?加到?/home/git-test/.git
$?git?--git-dir?/home/git-test/.git?add?.
--work-tree參數(shù)就允許你指定其他的項目目錄。/home/react-test?下檢出分支:#?默認(rèn)從?/home/react-test/.git?檢出
$?git?checkout?dev-test
#?從?/home/git-test/.git?檢出
$?git?--work-tree?/home/git-test/.git?checkout?dev-test
/opt/react-test.git?這個 git 倉庫的?release?分支,檢出(checkout)到項目目錄?/home/react-test,從而更新了項目目錄的代碼。nginx 解析
$?cd?/etc/nginx/conf.d
$?vim?react-test.conf
server?{
????listen?80;
????server_name?yourhost;?#?如?www.baidu.com
????root?/home/react-test/build;?#?指向打包后的目錄
????location?/?{
????????index?index.html;
????}
}
nginx -s reload,這樣解析就配好了!客戶端
react-test.git,回到客戶端只需要做一件事:將代碼推到這個裸倉庫。推送代碼
$?git?remote?add?prod?ssh://[email protected]/opt/react-test.git
$?git?checkout?-b?release
$?git?push?prod?release
post-receive?中寫好的輸出。當(dāng)推送完成,查看服務(wù)器下的 /home/react-test 目錄,會看到源文件和打包后的?build?文件評論
圖片
表情
