Skip to content

nuxt一键部署

date: 2020-05-03 21:00:00 tags: [linux,vue,nginx]

项目配置参考nuxt部署

在根目录下新建deploy文件夹

在deploy文件夹下新建 .env.dev 文件, 内容

bash
$ VUE_APP_SERVER_ID=0

在deploy文件夹下新建 .env.prod 文件, 内容

bash
$ VUE_APP_SERVER_ID=1

在deploy文件夹下新建 index.js 内容

bash
    const scpClient = require('scp2');
const ora = require('ora');
const chalk = require('chalk');
const fs = require('fs')
const {NodeSSH} = require('node-ssh')
const ssh = new NodeSSH()


const server = require('./products');
const spinner = ora('正在发布到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器...');
spinner.start();
scpClient.scp(
  './.nuxt', // 这个路径是你需要上传到服务器的文件夹
  {
    host: server.host,
    port: server.port,
    username: server.username,
    password: server.password,
    path: server.path + '/.nuxt'
  },
  function (err) {
    spinner.stop();
    if (err) {
      console.log(chalk.red('发布失败.\n'));
      throw err;
    } else {
      console.log(chalk.green('Success! 成功发布1到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器! \n'));
      fun2()
    }
  }
);


var fun2 = () => {
  scpClient.scp(
    './static',
    {
      host: server.host,
      port: server.port,
      username: server.username,
      password: server.password,
      path: server.path + '/static'
    },
    function (err) {
      spinner.stop();
      if (err) {
        console.log(chalk.red('发布失败.\n'));
        throw err;
      } else {
        console.log(chalk.green('Success! 成功发布2到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器! \n'));
        fun3()
      }
    }
  );
}

var fun3 = () => {
  scpClient.scp(
    './package.json',
    {
      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'));
        throw err;
      } else {
        console.log(chalk.green('Success! 成功发布3到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器! \n'));
        fun4()
      }
    }
  );
}


var fun4 = () => {
  scpClient.scp(
    './nuxt.config.js',
    {
      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'));
        throw err;
      } else {
        console.log(chalk.green('Success! 成功发布4到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器! \n'));
        fun5()
      }
    }
  );
}

var fun5 = () => {

  scpClient.scp(
    './deploy/deploy.sh',
    {
      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'));
        throw err;
      } else {
        console.log(chalk.green('Success! 成功发布5到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器! \n'));
        fun6()
      }
    }
  );
}


/**
 * 执行ssh命令
 */
var fun6 = () => {
  ssh.connect({
    host: server.host,
    username: server.username,
    password: server.password,
    port:22
  }).then(function () {
    ssh.execCommand('sh deploy.sh', { cwd: server.path }).then(function(result) {
      console.log('远程STDOUT输出: ' + result.stdout)
      console.log('远程STDERR输出: ' + result.stderr)
      if (result.stderr){
        console.log('发布成功!');
        process.exit(0);
      }
    });
  }).catch(err=>{
    console.log('ssh连接失败:',err);
    process.exit(0);
  });
}

在deploy文件夹下新建 products.js 内容

bash
/*
  *读取env环境变量
  */
const fs = require('fs');
const path = require('path');
// env 文件 判断打包环境指定对应的服务器id
const envfile = process.env.NODE_ENV === 'prod' ? './.env.prod' : './.env.dev';
// env环境变量的路径
const envPath = path.resolve(__dirname, envfile);
// env对象
const envObj = parse(fs.readFileSync(envPath, 'utf8'));
const SERVER_ID = parseInt(envObj['VUE_APP_SERVER_ID']);

function parse(src) {
  // 解析KEY=VAL的文件
  const res = {};
  src.split('\n').forEach(line => {
    // matching 'KEY' and 'VAL' in 'KEY=VAL'
    // eslint-disable-next-line no-useless-escape
    const keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
    // matched?
    if (keyValueArr != null) {
      const key = keyValueArr[1];
      let value = keyValueArr[2] || '';

      // expand newlines in quoted values
      const len = value ? value.length : 0;
      if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
        value = value.replace(/\\n/gm, '\n');
      }

      // remove any surrounding quotes and extra spaces
      value = value.replace(/(^["']|['"]$)/g, '').trim();

      res[key] = value;
    }
  });
  return res;
}

/*
  *定义多个服务器账号 根据 SERVER_ID 导出当前环境服务器账号
  */
const SERVER_LIST = [
  {
    id: 0,
    name: 'A-测试环境',
    domain: '',// 域名
    host: '1.1.1.1',// ip
    port: 22,// 端口
    username: 'root', // 登录服务器的账号
    password: 'root',// 登录服务器的账号
    path: '/run/www/nuxt'// 发布至静态服务器的项目路径
  },
  {
    id: 1, 
    name: 'B-正式环境',
    domain: '',// 域名
    host: '1.1.1.1',// ip
    port: 22,// 端口
    username: 'root', // 登录服务器的账号
    password: 'root',// 登录服务器的账号
    path: '/run/www/nuxt'// 发布至静态服务器的项目路径
  }
];

module.exports = SERVER_LIST[SERVER_ID];

在deploy文件夹下新建 deploy.sh 内容

bash
#!/bin/sh
cnpm install

# 查看pm2进程
pm2 list
# 删除name为first的进程
pm2 delete first
# 启动命令 name为first 的进程
pm2 start npm --name first -- start

# 服务端设置权限,执行命令 chmod +x ./deploy.sh

在配置文件package.json

bash
"scripts": {
  "serve": "vue-cli-service serve",
  "build": "vue-cli-service build",
  //注意新增类容里面需要下载辅助插件
  "deploy:dev": "npm run build && cross-env NODE_ENV=dev node ./deploy"
  "deploy:prod": "npm run build && cross-env NODE_ENV=prod node ./deploy"
}

下载对应安装包

bash
$ npm i -D cross-env scp2 ora ssh

服务端设置权限

deploy.sh 上传到服务端项目目录下

bash
$ cd 路径
$ chmod +x ./deploy.sh

服务端设置pm2

使用命令打包上传

bash
$ npm run deploy:dev

京ICP备2024093538号-1