index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import Client from 'ssh2-sftp-client';
  2. import chalk from 'chalk';
  3. import ora from 'ora';
  4. import shell from 'shelljs';
  5. import path from 'path';
  6. import { fileURLToPath } from 'url';
  7. import { config } from './config.js';
  8. const rawArgv = process.argv.slice(2);
  9. const filterStage = rawArgv.includes("--prod") ? "prod" : "test";
  10. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  11. // 构建
  12. const compileDist = async () => {
  13. console.log(chalk.blue("项目开始构建"));
  14. if (shell.exec(`npm run build:${filterStage}`).code === 0) {
  15. console.log(chalk.blue("项目构建成功"));
  16. }
  17. }
  18. // 获取配置
  19. const getConfig = () => {
  20. const [ result ] = config.filter(({ nodeEnv }) => nodeEnv === filterStage);
  21. return result;
  22. }
  23. // 部署
  24. const connectShell = async () => {
  25. const sftp = new Client();
  26. const item = getConfig();
  27. let spinner = null;
  28. // 打印信息
  29. const printMsg = ({ color, text }) => {
  30. console.log(chalk.red(`${item.host} --> `) + chalk[color](text));
  31. }
  32. printMsg({color: 'green', text: '服务器连接中'});
  33. sftp.connect({
  34. host: item.host,
  35. port: item.port,
  36. username: item.username,
  37. password: item.password,
  38. })
  39. .then(() => {
  40. printMsg({color: 'green', text: '服务器连接成功'});
  41. printMsg({color: 'yellow', text: '执行删除文件中'});
  42. return sftp.rmdir(item.path, true);
  43. })
  44. .then(() => {
  45. printMsg({color: 'green', text: '执行删除文件成功'});
  46. printMsg({color: 'green', text: '即将开始上传'});
  47. spinner = ora().start();
  48. spinner.text = '文件上传中,请等待'
  49. return sftp.uploadDir(path.resolve(__dirname, "../dist"), item.path);
  50. })
  51. .then(() => {
  52. spinner.info('文件上传结束')
  53. spinner.stop();
  54. printMsg({color: 'green', text: '上传完成,部署成功'});
  55. sftp.end();
  56. })
  57. .catch((err) => {
  58. console.error(
  59. err,
  60. chalk.red(`${item.host} -->`) + chalk.red(`上传失败`)
  61. );
  62. sftp.end();
  63. });
  64. }
  65. async function runStart() {
  66. await compileDist();
  67. await connectShell();
  68. }
  69. runStart();