Vue-CLI3.x automatically deploys projects to the server

Vue-CLI3.x automatically deploys projects to the server

Preface

The usual process for deploying front-end projects is: deploy to the test environment first and then release to the production environment. When deploying to the test environment, use xshell to connect to the server, then use xftp to connect to the server, then build the project locally, and then upload the built file to the server via xftp. The whole process feels a bit cumbersome and repetitive.

This tutorial explains the Vue project built with Vue-CLI 3.x scaffolding, and uses scp2 to automatically deploy to the static file server Nginx

1. Install scp2

scp2 is an enhanced implementation based on ssh2, written purely in JavaScript.
And ssh2 is a simulation implementation of SSH2 using nodejs. scp is the abbreviation of secure copy. scp is a command for secure remote file copying based on SSH login in Linux system. We will use this function here. After Vue is compiled and built successfully, the project will be pushed to the test/production environment 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. In the project root directory, create a .env.dev file (test environment variables)

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

// VUE_APP_SERVER_ID=0 in .env.dev file

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

The VUE_APP_SERVER_ID variable indicates that the current production server ID to be deployed is 1

// VUE_APP_SERVER_ID=1 in .env.prod file

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

/*
 *Read env environment variables*/
const fs = require('fs');
const path = require('path');
// The env file determines the server id corresponding to the packaging environment
const envfile = process.env.NODE_ENV === 'prod' ? '../.env.prod' : '../.env.dev';
// env environment variable path 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 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 into the server password: 'root', // Account for logging into the server path: '/mdm/nginx/dist' // Project path published 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];

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('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 and customize the name to "deploy".

The command to publish to the test environment is npm run deploy:dev, and the command to publish to 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 cross_env is used here, you need to install npm i --save-dev cross-env cross-env can set and use environment variables across platforms. Here it is used to set whether it is a production environment or a test environment.

Conclusion

Replenish

An enthusiastic friend said that the hash value is different each time the package is packed, so there will be more and more files in dist. You can use ssh2 to delete the dist file first, restart nginx after deletion, and then 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(
  'Publishing to' +
    (process.env.NODE_ENV === 'prod' ? 'production' : 'test') +
    'server...'
);

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

var conn = new Client();
conn
  .on('ready', function() {
    //rm deletes the dist file, \n is a line break to execute the restart nginx command. I am using docker to restart nginx here.
    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 the shell command, put the code to start uploading and deploying the 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

This is the end of this article about the steps of Vue-CLI3.x automatic deployment of projects to the server. For more related Vue-CLI3.x automatic deployment of projects, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to automatically deploy vue-cli3 project to the server after packaging
  • Vue-CLI 3 scp2 automatic deployment of projects to the server method

<<:  The most common mistakes in HTML tag writing

>>:  How to install Postgres 12 + pgadmin in local Docker (support Apple M1)

Recommend

A solution to a bug in IE6 with jquery-multiselect

When using jquery-multiselect (a control that tra...

Basic operation tutorial of files and permissions in centos

Preface Before we begin, we should briefly unders...

Detailed explanation of MySQL precompilation function

This article shares the MySQL precompilation func...

Detailed explanation of Linux text processing tools

1. Count the number of users whose default shell ...

Advertising skills in the Baidu Union environment (graphic tutorial)

Recently, students from the User Experience Team o...

Calling the search engine in the page takes Baidu as an example

Today, it suddenly occurred to me that it would be...

Docker online and offline installation and common command operations

1. Test environment name Version centos 7.6 docke...

Details of the underlying data structure of MySQL indexes

Table of contents 1. Index Type 1. B+ Tree 2. Wha...

A brief discussion on React native APP updates

Table of contents App Update Process Rough flow c...

Specific use of lazy loading and preloading in js

Delayed loading (lazy loading) and preloading are...

javascript to switch pictures by clicking a button

This article example shares the specific code of ...

Common front-end JavaScript method encapsulation

Table of contents 1. Enter a value and return its...

HTML imitates Baidu Encyclopedia navigation drop-down menu function

HTML imitates the Baidu Encyclopedia navigation d...