The Vue service plugin attempts to upload the package to the server

Time:2021-8-1

Vue plug-in

Vue plug-ins are divided into two types: cli plug-ins and service plug-ins

Service plug-in

  • The service plug-in will be automatically loaded when a service instance is created — for example, every time  vue-cli-service  When a command is invoked in a project.
  • The plug-in we want to complete next is executing the commandvue-cli-service publishWill be executed.
  • This is a plug-in that automatically pushes packaged files to the server. Let’s describe the steps to complete the plug-in:
    1. Registration command: register the command to execute the plug-in in package. JSONvue-cli-service publish
    2. Declare plug-ins: Vue plug-ins need to be registered. If they are not registered, Vue cannot identify which plug-ins publish points to. Therefore, we need to declare the service plug-ins through vueplugins in package.json.
    3. Register plug-ins: register plug-ins using the registercommand syntax of the service plug-in
    4. Write a plug-in: the plug-in needs to compress the dist folder into a compressed package, and then upload the compressed package to the file of the replacement server, which requiresarchiverCompressed files,ssh2Connect to the server, so you need to install these two packages before writing code. Remember to add themdevFor the development environment. If you ask me which package, NPM search. Yes, this sentence is written for myself.

1. Registration order

Add the publish command in the script

"scripts": {
    "publish": "vue-cli-service publish",
  },

2. Declaration plug-in

  "vuePlugins": {
    "service": [
      "./publish/vue-cli-plugin-publish"
    ]
  },

3. Register plug-ins

  • Create a new publish folder in the root directory to store the relevant files of the publish plug-in
  • Create a new vue-cli-plugin-publish.js file in this directory and add the following code to complete the registration of a service plug-in
    module.exports = (api, projectOptions) => {
    //Built in command
    api.registerCommand('publish', {
    Description: 'auto build deployment',
    usage: 'vue-cli-service publish',
    options: {}
    }, (args) => {
    //Write the plug-in function here
    })
    }

4. Write a plug-in

  • Next, let’s add the code of the plug-in function
  • In the previous vue-cli-plugin-publish.js file, add the following codes at the beginning and middle respectively
    const config = require('./config')
    const fs = require('fs')
    const archiver = require('archiver')
  • Insert into the location of the plug-in function. Of course, we can also create a new file and reference this method in the form of require.

    4.1 compressed files

    (function() {
      // console.log(chalk.cyan('  Zip files.\n'))
      //Locate the dist folder and create a compressed package
      var output = fs.createWriteStream(`publish/${config.title}.zip`)
      var archive = archiver('zip')
      console.log('in zip ~~~~~~~~~~~~')
    
      output.on('close', function() {
        // console.log(chalk.cyan('  Zip files.\n'))
        // console.timeEnd('key')
        console.log('compress completed...ready upload')
        //After compression, upload the file. Here I put the logic of uploading the file in the publish.js file
        require('./publish')()
      })
    
      output.on('end', function() {
      })
    
      archive.on('error', function(err) {
        throw err
      })
    
      archive.pipe(output)
      archive.glob('./dist' + '/**')
      archive.finalize()
    })()

    4.2 uploading files

  • OK, create a new publish. JS file and put the code in it.
const chalk = require('chalk')
//The use of shh2 simulates a server
var Client = require('ssh2').Client
//Create a connection
var conn = new Client()
//All the friends who have written node know that FS is used to read and write files. Read the documents yourself. After all, I don't always remember
//The link is here http://nodejs.cn/api/fs.html#fs_ file_ system
var fs = require('fs')
//This is the configuration file
const defaultSettings = require('./config')

/**
 *1. Enter the directory
 *2. Delete old backup items
 *3. Add the BAK flag to the original project name as the backup file
 *4. Unzip the uploaded zip file and change the name to the project name
 *5. Delete the zip file
 *6. Exit
 * @type {string[]}
 */
const uploadShellList = [
  `cd ${defaultSettings.path}\n`,
  `rm -rf ${defaultSettings.title}.bak\n`,
  `mv ${defaultSettings.title} ${defaultSettings.title}.bak\n`,
  `unzip ${defaultSettings.title}.zip\n`,
  `mv dist ${defaultSettings.title}\n`,
  `rm -rf ${defaultSettings.title}.zip\n`,
  `exit\n`
]
const params = { file: `./publish/${defaultSettings.title}.zip`, target: `${defaultSettings.path}/${defaultSettings.title}.zip` }

function Ready() {
  conn.on('ready', function() {
    console.log('Client :: ready')
    UploadFile(conn, params)
  }).connect(defaultSettings)
}

/**
 *Upload file
 * @param conn
 * @param params
 * @constructor
 */
function UploadFile(conn, params) {
  const file = params.file
  const target = params.target

  if (!conn) {
    return
  }
  conn.sftp(function(err, sftp) {
    if (err) {
      throw err
    }
    sftp.fastPut(file, target, {}, function(err, result) {
      if (err) {
        console.log(chalk.red(err.message))
        throw err
      }
      Shell(conn)
    })
  })
}

/**
 *After the content to be uploaded by the server is completed
 *Delete local compressed files
 * @param conn
 * @constructor
 */
function Shell(conn) {
  conn.shell(function(err, stream) {
    if (err) throw err
    stream.on('close', function() {
      console.log('Stream :: close')
      conn.end()
      fs.unlinkSync(`./publish/${defaultSettings.title}.zip`)
    }).on('data', function(data) {
      console.log('STDOUT: ' + data)
    }).stderr.on('data', function(data) {
      console.log('STDERR: ' + data)
    })
    stream.end(uploadShellList.join(''))
  })
}

module.exports = function() {
  try {
    Ready()
  } catch (err) {
    console.log(err)
  }
}

Get the class, and the configuration file will also be released to you

  • Either privatekey or password is OK. Please choose by yourself
    module.exports = {
    Title: 'folder name after packaging',
    Host: 'is the server address you want to upload',
    port: 22,
    Username: 'user name',
    privateKey: require('fs').readFileSync('c:/Users/zmx/.ssh/id_rsa'),
    Path: 'folder address'
    }

Service plug-in supplement

Plug in parameters

  • If your configuration file wants to pass parameters when calling the plug-in, of course it can
  • Please open the vue.config.js file. If not, create one yourself.

    Transmission parameter

    //Vue.config.js related code
    module.exports = {
    pluginOptions: {
    publish: {
      //Vue cli plugin publish plug-in can access these options as' projectoptions. Pluginoptions. Publish ', and other plug-ins can also get them
      Param: 'pass parameters to built-in plug-ins'
    }
    }
    }

    Take ginseng

    module.exports = (api, projectOptions) => {
    api.registerCommand('publish', {
    Description: 'auto build deployment',
    usage: 'vue-cli-service publish',
    options: {}
    }, (args) => {
    //Output parameters passed in
    //Projectoptions gets the configuration exposed in the vue.config.js file
    console.log(projectOptions.pluginOptions.publish.param)
    })
    }

    Configuration module

    module.exports = (api, projectOptions) => {
    api.chainWebpack(webpackConfig => {
    //Modify webpack configuration through webpack chain
    })
    
    api.configureWebpack(webpackConfig => {
    //Modify webpack configuration
    //Or return the configuration object merged through webpack merge
    })
    
    api.registerCommand('test', args => {
    //Register ` Vue cli service test`
    })
    }

vue

This work adoptsCC agreement, reprint must indicate the author and the link to this article