Search code examples
vue.jsvue-clivue-cli-3

Vue-cli-service serve build completion callback?


I'd like to fire up a vue-cli dev server, then run a command from node once this build has completed.

Is there a way to run vue-cli-service serve from a node script so that I can receive a callback once the dev server is up and running?


Solution

  • vue-cli-service.js does not return the service promise (which would've allowed you to setup a completion callback), but you could make a copy of the script (25 lines) to do so:

    my-vue-cli-service.js:

    #!/usr/bin/env node
    const semver = require('semver')
    const { error } = require('@vue/cli-shared-utils')
    const requiredVersion = require('@vue/cli-service/package.json').engines.node
    
    if (!semver.satisfies(process.version, requiredVersion)) {
      error(
        `You are using Node ${process.version}, but vue-cli-service ` +
        `requires Node ${requiredVersion}.\nPlease upgrade your Node version.`
      )
      process.exit(1)
    }
    
    const Service = require('@vue/cli-service')
    const service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd())
    
    const rawArgv = process.argv.slice(2)
    const args = require('minimist')(rawArgv)
    const command = args._[0]
    
    module.exports = () =>  // <--- add this line to return the service promise
      service.run(command, args, rawArgv).catch(err => {
        error(err)
        process.exit(1)
      })
    

    Then, you could create another script that consumes this copy, adding a then callback to be invoked when the server started successfully:

    my-service.js:

    #!/usr/bin/env node
    const service = require('./my-vue-cli-service')
    
    service().then(result => {
      if (result && result.server) {  // <--- server started successfully if result.server exists
        const {server, url} = result;
        console.log('ready');
      }
    })
    

    Be sure to update package.json to use the new script:

    package.json:

    {
      "scripts": {
        "serve": "./my-service.js serve"
      }
    }