preface

The usual front-end project deployment process is as follows: Deploy to the test environment and release to the production environment. Connect to the server using Xshell when deploying to the test environment, and then connect to the server using XFTP. Then local build project, and upload the build file to the server through XFTP.

This tutorial is about vuE-CLI 3.x scaffolding of a Vue project that is automatically deployed to the static file server Nginx using SCP2

An installation scp2

Scp2 is an sSH2-based enhanced implementation written purely in JavaScript. Ssh2 is a simulated implementation of SSH2 using NodeJS. SCP is short for Secure Copy. SCP is a secure remote file copy command based on SSH login in Linux. Here we use this feature to push the project to the test/production environment after a successful Vue build to facilitate testing and improve efficiency. Install scp2:

npm install scp2 --save-dev
Copy the code

2. Configure SSH remote login accounts for the test and production servers

1. In the project root directory, create the.env.dev file (test environment variables).

VUE_APP_SERVER_ID Indicates that the ID of the test server to be deployed is 0

VUE_APP_SERVER_ID=0 in //.env.devCopy the code

2. In the project root directory, create the.env.prod file (production environment variables).

VUE_APP_SERVER_ID Indicates that the ID of the production server to be deployed is 1

VUE_APP_SERVER_ID=1 in the.env.prod fileCopy the code

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


/* * Read the env environment variable */
const fs = require('fs');
const path = require('path');
// env specifies the server ID for the packaging environment
const envfile = process.env.NODE_ENV === 'prod' ? '.. /.env.prod' : '.. /.env.dev';
// env Specifies the path of the 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) {
  // parse the file with 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;
}

/* * Define multiple server accounts and export the current environment server account */ based on the SERVER_ID
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'.// Account for logging in to the server
    password: 'root'.// Account for logging in to the server
    path: '/mdm/nginx/dist'// Publish the project path to the 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];


Copy the code

3. Use the SCP2 library to create automated deployment scripts

In 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('Posting 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('Publishing failed.\n'));
      throw err;
    } else {
      console.log(chalk.green('Success! Successfully published to ' + (process.env.NODE_ENV === 'prod' ? 'production' : 'test') + 'Server! \n')); }});Copy the code

Add package.json to scripts and set the name to “deploy”

Run the NPM run deploy:dev command to the test environment and NPM run deploy:prod command to the production environment

  "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",},Copy the code

NPM I –save-dev cross-env cross-env can set and use environment variables across platforms.

The illustration

supplement

You can use ssh2 to delete the dist file first, and then restart nginx to upload it to the server.

/ / deploy/index. Js
const scpClient = require('scp2');
const ora = require('ora');
const chalk = require('chalk');
const server = require('./products');
const spinner = ora(
  'Posting 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 file, \n is newline, execute restart nginx command
    conn.exec('rm -rf /mdm/nginx/dist\ndocker restart nginx'.function(err, stream) {
      if (err) throw err;
      stream
        .on('close'.function(code, signal) {
          // After executing shell command, put the start upload deployment project code in this
          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('Publishing 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')
  });

Copy the code

conclusion

Welcome to correct, Vue learning group 493671066 welcome to join my front-end learning communication group to learn and progress together.

Refer to the articlewww.cnblogs.com/sufaith/p/v…