Vue-CLI 3.X 部署项目至生产服务器的方法
本教程主要讲解的是Vue-CLI3.x脚手架搭建的vue项目,先构建生成dist文件(纯静态应用),然后自动化部署到静态文件服务器Nginx。
一、Nginx服务器文件的配置
server{
listen80;
server_namewww.xxxxxx.com;#生产环境
location/{
root/usr/local/www/xxx_program/;
indexindex.html;
try_files$uri$uri//index.html;
}
}
server{
listen80;
server_nametest.xxxxxx.com;#测试环境
location/{
root/usr/local/www/xxx_program_test/;
indexindex.html;
try_files$uri$uri//index.html;
}
}
二、配置生产/测试环境服务器SSH远程登陆账号
在项目根目录下,创建.env文件(当前环境变量)
VUE_APP_SERVER_ID变量指代当前需部署的服务器ID为0
VUE_APP_SERVER_ID=0
在项目根目录下,创建deploy/products.js文件
该文件功能如下:
(1)读取env环境变量
constfs=require('fs')
constpath=require('path')
//env环境变量的路径
constenvPath=path.resolve(__dirname,'../.env')
//env对象
constenvObj=parse(fs.readFileSync(envPath,'utf8'))
constSERVER_ID=parseInt(envObj['VUE_APP_SERVER_ID'])
functionparse(src){
//解析KEY=VAL的文件
constres={}
src.split('\n').forEach(line=>{
//matching"KEY'and'VAL'in'KEY=VAL'
constkeyValueArr=line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/)
//matched?
if(keyValueArr!=null){
constkey=keyValueArr[1]
letvalue=keyValueArr[2]||''
//expandnewlinesinquotedvalues
constlen=value?value.length:0
if(len>0&&value.charAt(0)==='"'&&value.charAt(len-1)==='"'){
value=value.replace(/\\n/gm,'\n')
}
//removeanysurroundingquotesandextraspaces
value=value.replace(/(^['"]|['"]$)/g,'').trim()
res[key]=value
}
})
returnres
}
(2)定义多个服务器账号及根据SERVER_ID导出当前环境服务器账号
constSERVER_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文件
constscpClient=require('scp2')
constora=require('ora')
constchalk=require('chalk')
constserver=require('./products')
constspinner=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'))
throwerr
}else{
console.log(chalk.green('Success!成功发布到生产服务器!\n'))
}
})
四、添加package.json中的scripts命令,自定义名称为“deploy”
"scripts":{
"serve":"vue-cli-serviceserve",
"build":"vue-cli-servicebuild",
"lint":"vue-cli-servicelint",
"deploy":"npmrunbuild&&node./deploy"
}
五、执行部署任务
在项目根目录下执行npmrundeploy命令,或使用vueui控制面板执行deploy任务,即可自动打包并部署至线上服务器
备注:要切换部署的服务器,只需修改.env文件中的服务器ID,然后再执行deploy任务即可.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。