部署scp2自动上传到服务器
vue-cli项目+scp2 编译后,部署到服务器
注意公开类型的项目请不要上传配置到远程仓库
npm run build // 构建
npm run deploy // 部署到服务器
我的项目是vue-cli +宝塔 后端用fastadmin。
每次修改完vue的文件后都要打包,压缩,上传,解压十分麻烦。因此配合scp自动化完成这一系列步骤是十分舒服的事情。配置很简单
- 安装依赖
npm i scp2 ora read chalk -D
- 服务器信息 deploy.config.js
- 添加npm命令
一. 根目录(与package.json同级)创建deploy.config.js
文件
// deploy.config.js
module.exports = {
production: {
ssh: {
host: '', //ip地址
username: '', //用户名
password: '' // 密码
},
distPath: '', // 线上要放 dist文件夹的目录 如: public/
targetPath: '', // 目录 如: /www/wwwroot/xxx/
checkBranch: false
}
}
二. 根目录(与package.json同级)创建deploy.js
文件
// deploy.js ---------------------------------------------------
const scpClient = require('scp2')
// node模块 - node.js 命令行环境的 loading效果和显示各种状态的图标
const ora = require('ora')
const chalk = require('chalk')
const read = require('read')
const path = require('path')
function upload (server) {
// 命令 提示文本
console.log(chalk.green('Scp2发布模式-->请确认发布信息:'))
console.log(chalk.green('> 环境:' + server.name))
console.log(chalk.green('> 服务器:' + server.username + '@' + server.host))
console.log(chalk.green('> 服务器发布路径:' + server.path))
read({
prompt: '确定执行发布操作吗?(yes/no)'
},
async (err, text) => {
if (err) {
console.log('err', err.stack)
}
const spinner = ora(
'正在发布到' +
(process.env.NODE_ENV === 'prod' ? '生产' : '测试') +
'服务器...'
)
// loading
spinner.start()
if (text === 'yes') {
// 执行scp2库,上传文件
// 第一个参数:要上传到服务器的文件
// 第二个参数:服务器配置
// 第三个参数:上传回调函数
scpClient.scp(
'./dist/', { // 本地项目目录
host: server.host,
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(
(process.env.NODE_ENV === 'production' ? '生产' : '测试') +
'服务器部署完成!\n'
)
)
}
}
)
} else {
spinner.stop()
}
}
)
}
// 获取配置
const rcPath = path.resolve('deploy.config.js')
const oldConfig = require(rcPath)
const serverZeploy = oldConfig['production']
const server = {
name: process.env.NODE_ENV,
username: serverZeploy.ssh.username,
password: serverZeploy.ssh.password,
host: serverZeploy.ssh.host,
path: serverZeploy.targetPath + '/' + serverZeploy.distPath
}
upload(server)
三. 在package.json 加入一行 "deploy": "node deploy.js"
运行效果
本作品采用《CC 协议》,转载必须注明作者和本文链接
不过用户名密码、主机与端口都暴露出来写到版本控制里边去,有点危险吧
请问这种方式适用于cli2.9.6吗
@xianzicheng 你说的Vue CLI吗?不要求vue的版本,其实只要求scp的配置文件符合他的版本