本教程主要講解的是 Vue-CLI 3.x 腳手架搭建的vue項目, 先構建生成dist文件(純靜態應用), 而後自動化部署到靜態文件服務器 Nginx。html
1、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;
}
}複製代碼
2、配置生產/測試環境 服務器SSH遠程登錄帳號vue
VUE_APP_SERVER_ID變量指代 當前需部署的服務器ID爲0node
VUE_APP_SERVER_ID=0複製代碼
2. 在項目根目錄下, 建立 deploy/products.js 文件vue-cli
該文件功能以下:npm
(1) 讀取env環境變量json
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 導出當前環境服務器帳號bash
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]複製代碼
3、建立自動化部署腳本 (使用scp2庫)服務器
在項目根目錄下, 建立 deploy/index.js 文件dom
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'))
}
})複製代碼
4、添加 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"
}複製代碼
5、執行部署任務
在項目根目錄下 執行 npm run deploy命令, 或 使用 vue ui控制面板執行deploy任務, 便可自動打包並部署至線上服務器
備註: 要切換部署的服務器, 只需修改 .env文件中的服務器ID, 而後再執行deploy任務便可.
福利: 本文已同步到個人我的技術網站 IT乾貨-sufaith 該網站包括Python, Linux, Nodejs, 前端開發等模塊, 專一於程序開發中的技術、經驗總結與分享, 歡迎訪問.