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

Bugs encountered when using mybatis-generator with mysql8.0.3 in IDEA

1. Add the plug-in and add the following configur...

In-depth understanding of Vue-cli4 routing configuration

Table of contents Preface - Vue Routing 1. The mo...

Nginx improves access speed based on gzip compression

1. Why does nginx use gzip? 1. The role of compre...

Install multiple versions of PHP for Nginx on Linux

When we install and configure the server LNPM env...

Tutorial diagram of installing TomCat in Windows 10

Install TomCat on Windows This article will intro...

Detailed explanation of the reasons why MySQL connections are hung

Table of contents 1. Background Architecture Prob...

3D tunnel effect implemented by CSS3

The effect achievedImplementation Code html <d...

WeChat applet custom tabbar component

This article shares the specific code of the WeCh...

How to install golang under linux

Go is an open source programming language that ma...

How to limit the number of records in a table in MySQL

Table of contents 1. Trigger Solution 2. Partitio...

Analysis of the process of deploying pure HTML files in Tomcat and WebLogic

1. First, the pure HTML file must have an entry i...

Exploring the use of percentage values ​​in the background-position property

How background-position affects the display of ba...