Vue CLI3.x Method steps for automatically deploying a project to a server

  • 2021-12-04 09:18:54
  • OfStack

Preface to the table of contents 1 Install scp2 2. Configure the SSH remote login account information of the test/production environment server 3. Create automated deployment scripts using the scp2 library 4. Add the scripts command from package. json with a custom name of "deploy", Concluding remarks

Preface

Usually, the front-end project deployment process is: first deploy to the test environment ok, then publish to the production environment, deploy to the test environment to connect to the server with xshell, then connect to the server with xftp, then local build project, and then upload build files to the server through xftp. The whole process feels slightly tedious and repetitive.

This tutorial describes the vue project built on the Vue-CLI 3. x scaffold, using scp2 to automate deployment to the static file server Nginx

1 Install scp2

scp2 is an enhanced implementation based on ssh2, written purely using JavaScript.
ssh2 is a simulation implementation of SSH2 using nodejs. scp is the abbreviation of secure copy, and scp is a safe remote file copy command based on SSH login under Linux system. Here, we use this function to push the project to the test/production environment after the successful compilation and construction of Vue, so as to facilitate testing and improve efficiency.

Install scp2:


npm install scp2 --save-dev

2. Configure the SSH remote login account information of the test/production environment server

1. Under the project root, create the. env. dev file (test environment variable)

The VUE_APP_SERVER_ID variable indicates that the test server currently to be deployed has an ID of 0


// .env.dev In a file 
VUE_APP_SERVER_ID=0

2. Under the project root, create the. env. prod file (production environment variable)

The VUE_APP_SERVER_ID variable indicates that the current production server to be deployed has an ID of 1


// .env.prod In a file 
VUE_APP_SERVER_ID=1

3. Under the project root directory, create the deploy/products. js file


/*
 * Read env Environment variable 
 */
const fs = require('fs');
const path = require('path');
// env  Documents   Determine the corresponding server specified by the packaging environment id
const envfile = process.env.NODE_ENV === 'prod' ? '../.env.prod' : '../.env.dev';
// env Path of environment variable 
const envPath = path.resolve(__dirname, envfile);
// env Object 
const envObj = parse(fs.readFileSync(envPath, 'utf8'));
const SERVER_ID = parseInt(envObj['VUE_APP_SERVER_ID']);

function parse(src) {
  //  Analyse KEY=VAL File of 
  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;
}

/*
 * Define multiple server accounts   And   According to  SERVER_ID  Export the current environment server account number 
 */
const SERVER_LIST = [
  {
    id: 0,
    name: 'A- Production environment ',
    domain: 'www.prod.com',//  Domain name 
    host: '46.106.38.24',// ip
    port: 22,//  Port 
    username: 'root', //  Log in to the server account number 
    password: 'root',//  Log in to the server account number 
    path: '/mdm/nginx/dist'//  Project path published to static server 
  },
  {
    id: 1,
    name: 'B- Test environment ',
    domain: 'test.xxx.com',
    host: 'XX.XX.XX.XX',
    port: 22,
    username: 'root',
    password: 'xxxxxxx',
    path: '/usr/local/www/xxx_program_test/'
  }
];

module.exports = SERVER_LIST[SERVER_ID];

3. Create automated deployment scripts using the scp2 library

Under the project root directory, create the deploy/index. js file


const scpClient = require('scp2');
const ora = require('ora');
const chalk = require('chalk');
const server = require('./products');
const spinner = ora(' Publishing to ' + (process.env.NODE_ENV === 'prod' ? ' Production ' : ' Test ') + ' Server ...');
spinner.start();
scpClient.scp(
  'dist/',
  {
    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(' Publish failed .\n'));
      throw err;
    } else {
      console.log(chalk.green('Success!  Successfully published to ' + (process.env.NODE_ENV === 'prod' ? ' Production ' : ' Test ') + ' Server ! \n'));
    }
  }
);

4. Add the scripts command in package. json with a custom name of "deploy",

The publish to test environment command is npm run deploy: dev, and the production environment is npm run deploy: prod


  "scripts": {
    "serve": "vue-cli-service serve --mode dev",
    "build": "vue-cli-service build --mode prod",
    "deploy:dev": "npm run build && cross-env NODE_ENV=dev node ./deploy",
    "deploy:prod": "npm run build && cross-env NODE_ENV=prod node ./deploy",
  },

ps here uses the installation of cross_env npm i--save-dev cross-env cross-env can set and use environment variables across platforms, which is used here to set whether it is a production environment or a test environment.

Concluding remarks

Supplement

Some enthusiastic friends said that every time hash values are different, there are more and more files in dist. You can use ssh2 to delete dist files first, restart nginx after deletion and upload them to the server.


//  deploy/index.js Inside 
const scpClient = require('scp2');
const ora = require('ora');
const chalk = require('chalk');
const server = require('./products');
const spinner = ora(
  ' Publishing to ' +
    (process.env.NODE_ENV === 'prod' ? ' Production ' : ' Test ') +
    ' Server ...'
);

var Client = require('ssh2').Client;

var conn = new Client();
conn
  .on('ready', function() {
    // rm  Delete dist Documents, \n  Is a line break   Line feed execution   Restart nginx Command   I'm here to use docker Restart nginx
    conn.exec('rm -rf /mdm/nginx/dist\ndocker restart nginx', function(
      err,
      stream
    ) {
      if (err) throw err;
      stream
        .on('close', function(code, signal) {
          //  In execution shell Command, put the code to start uploading the deployment project here 
          spinner.start();
          scpClient.scp(
            './dist',
            {
              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(' Publish failed .\n'));
                throw err;
              } else {
                console.log(
                  chalk.green(
                    'Success!  Successfully published to ' +
                      (process.env.NODE_ENV === 'prod'
                        ? ' Production '
                        : ' Test ') +
                      ' Server ! \n'
                  )
                );
              }
            }
          );

          conn.end();
        })
        .on('data', function(data) {
          console.log('STDOUT: ' + data);
        })
        .stderr.on('data', function(data) {
          console.log('STDERR: ' + data);
        });
    });
  })
  .connect({
    host: server.host,
    port: server.port,
    username: server.username,
    password: server.password
    //privateKey: require('fs').readFileSync('/home/admin/.ssh/id_dsa')
  });

Reference article https://www.cnblogs.com/sufaith/p/vue-cli.html


Related articles: