基於node.js實現前端web項目自動化部署

前言

前端項目部署時,nginx配置完成後,只需將打包後的文件上傳至服務器指定目錄下便可。 前端

通常使用如下方式完成:node

  • xshell 等命令行工具上傳
  • ftp/sftp 等可視化工具上傳
  • jenkins 等自動化部署服務 對於簡單前端項目,頻繁部署時,xshell、ftp兩種方式較爲繁瑣,而jenkins 等自動化部署服務須要提早安裝軟件、並熟悉配置流程。 所以但願藉助本地 node 服務實現對前端打包後文件的上傳工做,既不須要服務器額外安裝程序,還能夠幫助咱們實現快速上傳部署,更能幫助咱們深刻了解 node 。

目的

減小web項目在開發調試過程當中頻繁編譯打包後再使用ftp工具部署至服務器的手動過程,提升工做效率。nginx

1.導入依賴模塊

  1. npm install inquirer ssh2-sftp-client
  2. touch ssh.js helper.js
  3. 在package.json增長一個腳本,完成以後必定要 npm i 從新安裝依賴,確保新加入的腳本生效!
"scripts": {
	"test": "echo \"Error: no test specified\" && exit 1",
	"deploy": "bash deploy.sh"
},
複製代碼
  1. touch deploy.sh
npm run build
echo "打包完成"
node ./ssh.js

cd -
複製代碼

2. 鏈接遠端服務器並上傳操做

const Client = require('ssh2-sftp-client')
const sftp = new Client()
const helper = require ('./helper')
const config = [
  {
    name: 'a',  // 項目/服務器名稱
    ssh: {
      host: '192.168.0.105',
      port: 22,
      username: 'root',
      password: 'root',
    },
    romotePath: '/var/www/dist',// 遠程地址
    localPath:'./dist',// 本地地址
  },
  {
    name: 'b',
    ssh: {
      host: '192.168.0.110',
      port: 22,
      username: 'root',
      password: 'root',
    },
    romotePath: '/var/www/dist',
    localPath:'./dist',
  }
]

async function main() {
  const SELECT_CONFIG = (await helper(config)).value // 所選部署項目的配置信息
  console.log('您選擇了部署 ' + SELECT_CONFIG.name)
  sftp
    .connect(SELECT_CONFIG.ssh)
    .then(() => {
      console.log('- 鏈接成功,上傳中..')
      return sftp.uploadDir(SELECT_CONFIG.localPath, SELECT_CONFIG.romotePath)
    })
    .then(data => {
      console.log(data,' 上傳完成,及時清除緩存' )
    })
    .catch(err => {
      console.log(err,' 出錯了!快看看怎麼回事! ')
    })
    .finally(() => {
      sftp.end()// 斷開鏈接
    })
}

main()

複製代碼

3.構建和發佈

  • 執行 npm run deploy 就能夠打包並主動上傳到你的目標服務器
  • windows系統 Git Bash Use arrow keys沒法選擇
winpty npm.cmd run deploy
複製代碼

項目github地址。 歡迎star、留言、issue。 但願本文對各位有所幫助,祝工做生活愉快!git

相關文章
相關標籤/搜索