本文已同步到專業技術網站 www.sufaith.com, 該網站專注於前后端開發技術與經驗分享, 包含Web開發、Nodejs、Python、Linux、IT資訊等板塊.
本教程主要講解的是 Vue-CLI 3.x 腳手架搭建的vue項目, 先構建生成dist文件(純靜態應用), 然后自動化部署到靜態文件服務器 Nginx。
一、Nginx服務器文件的配置
server { listen 80; server_name www.xxxxxx.com;#生產環境 location / { root /usr/local/www/xxx_program/; index index.html; try_files $uri $uri/ /index.html; } } server { listen 80; server_name test.xxxxxx.com; #測試環境 location / { root /usr/local/www/xxx_program_test/; index index.html; try_files $uri $uri/ /index.html; } }
二、配置生產/測試環境 服務器SSH遠程登陸賬號
1. 在項目根目錄下, 創建 .env 文件 (當前環境變量)
VUE_APP_SERVER_ID變量指代 當前需部署的服務器ID為0
VUE_APP_SERVER_ID=0
2. 在項目根目錄下, 創建 deploy/products.js 文件
該文件功能如下:
(1) 讀取env環境變量
const fs = require('fs')
const path = require('path')
// env環境變量的路徑
const envPath = path.resolve(__dirname, '../.env')
// env對象
const envObj = parse(fs.readFileSync(envPath, 'utf8'))
const SERVER_ID = parseInt(envObj['VUE_APP_SERVER_ID'])
function parse (src) {
// 解析KEY=VAL的文件
const res = {}
src.split('\n').forEach(line => {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/)
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1]
let value = keyValueArr[2] || ''
// expand newlines in quoted values
const len = value ? value.length : 0
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, '\n')
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, '').trim()
res[key] = value
}
})
return res
}
(2) 定義多個服務器賬號 及 根據 SERVER_ID 導出當前環境服務器賬號
const SERVER_LIST = [ { id: 0, name: 'A-生產環境', domain: 'www.xxx.com', host: 'XX.XX.XX.XX', port: 22, username: 'root', password: 'xxxxxxx', path: '/usr/local/www/xxx_program/' }, { id: 1, name: 'B-測試環境', domain: 'test.xxx.com', host: 'XX.XX.XX.XX', port: 22, username: 'root', password: 'xxxxxxx', path: '/usr/local/www/xxx_program_test/' }, ] module.exports = SERVER_LIST[SERVER_ID]
三、創建自動化部署腳本 (使用scp2庫)
在項目根目錄下, 創建 deploy/index.js 文件
const scpClient = require('scp2')
const ora = require('ora')
const chalk = require('chalk')
const server = require('./products')
const spinner = ora('正在發布到生產服務器...')
spinner.start()
scpClient.scp('dist/', {
host: server.host,
port: server.port,
username: server.username,
password: server.password,
path: server.path
}, function(err) {
spinner.stop()
if (err) {
console.log(chalk.red(' 發布失敗.\n'))
throw err
} else {
console.log(chalk.green(' Success! 成功發布到生產服務器! \n'))
}
})
四、添加 package.json 中的 scripts 命令, 自定義名稱為 "deploy"
"scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint", "deploy": "npm run build && node ./deploy" }
五、執行部署任務
在項目根目錄下 執行 npm run deploy命令, 或 使用 vue ui控制面板執行deploy任務, 即可自動打包並部署至線上服務器

備注:
要切換部署的服務器, 只需修改 .env文件中的服務器ID, 然后再執行deploy任務即可.
福利:
本文已同步到我的個人技術網站 IT干貨-sufaith 該網站包括Python, Linux, Nodejs, 前端開發等模塊, 專注於程序開發中的技術、經驗總結與分享, 歡迎訪問.
