前端工程化 项目工程环境自动打包上传服务器

1.创建 deploy.js 放在package.json同一层级
/**
 * 结合scp2和ssh2将build打包传到服务器
 * npm install scp2 --save-dev
 * npm install ssh2 --save-dev
 * 
 * package.json中
 * scripts:{
 *  "deploy": "npm run build && node deploy"
 * }
 * npm run deploy
 * 单独测试deploy.js
 * node deploy
 */
const scpClient = require('scp2');
const ora = require('ora');
const chalk = require('chalk');
const spinner = ora('正在发布到生产服务器...');

//服务器相关配置
const server = {
	host: "服务器ip",
	port:端口,
	username:"root",
	password:"管理密码",
	path:"/home/HTML/vue/main/(上传文件路径)"
};

var Client = require('ssh2').Client;
var conn = new Client();
conn.on('ready', function() {
    console.log(chalk.green('准备删除文件'+server.path+'.\n'));
    conn.exec('rm -rf '+server.path, function(err, stream){
        if (err){
            console.log(chalk.red(err));
            conn.end();
        }else{
            conn.exec('mkdir '+server.path, function(err2, stream2){
                if (err){
                    console.log(chalk.red(err));
                    conn.end();
                }else{                
                    spinner.start();
                    scpClient.scp('dist/',server,function (err) {    
                        spinner.stop();
                        if (err) {
                            console.log(err);
                            console.log(chalk.red('发布失败.\n'));
                        } else {
                            console.log(chalk.green('Success! 成功发布到\n'+server.host+'\n'+server.path+'\n'));
                        }
                        conn.end();
                    });
                }
                
            });

        }
        
    })
}).connect({
    host: server.host,
    port: server.port,
    username: server.username,
    password: server.password
    //privateKey: require('fs').readFileSync('/home/admin/.ssh/id_dsa')
});

2.在package.json文件中定义相应的脚本 cmd执行指令: npm run deploy ,需要测试脚本的话可以用 node deploy
"deploy": "npm run build && node deploy", //先build本地打包 再通过deploy自定义的node脚本进行服务器上传
posted @ 2024-03-06 09:32  xiao旭  阅读(49)  评论(0编辑  收藏  举报