前端使用nodejs把vue项目打包后自动发布到服务器,不再求后端
1. 安装用到的依赖包
npm i ssh2 archiver -D
2. 在项目根目录创建release.js
// 自动发布脚本
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
/* ------------------ 请配置服务器信息 --- start --------------------- */
const zipName = 'dist.zip';
const remotePath = '/www/wwwroot/web/home'; // 要上传到服务器的目标路径
const distPath = './dist'; // 要压缩的文件夹路径
// 服务器配置信息
const sshConfig = {
host: '***.***.***.***',
port: 22,
username: '****',
password: '************',
};
/* ------------------ 配置服务器信息 --- end --------------------- */
const output = fs.createWriteStream(zipName); // 压缩后的文件
const archive = archiver('zip');
output.on('close', function () {
console.log(`${archive.pointer()} total bytes`);
console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('error', function (err) {
throw err;
});
archive.pipe(output);
const directoryPath = path.join(__dirname, distPath);
archive.directory(directoryPath, false);
archive.finalize();
const Client = require('ssh2').Client;
const conn = new Client();
conn
.on('ready', function () {
console.log('服务器连接成功');
conn.sftp(function (err, sftp) {
if (err) throw err;
const readStream = fs.createReadStream(zipName);
const writeStream = sftp.createWriteStream(remotePath + '/' + zipName);
readStream.pipe(writeStream);
writeStream.on('close', function () {
console.log(`File ${remotePath} 上传 完成`);
// 解压
conn.exec(`cd ${remotePath} && unzip -o ${zipName}`, function (err, stream) {
if (err) throw err;
stream
.on('close', function (code, signal) {
console.log('部署 完成');
// 删除本地压缩包
fs.unlinkSync(zipName);
conn.end();
})
.on('data', function (data) {
console.log('解压中: ' + data);
});
});
});
});
})
.connect(sshConfig);
3.打开package.json
增加发布脚本
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"release": "npm run build && node release.js" // ++++ 增加发布脚本
},
4.执行
npm run release