Vue-cli-service服务构建完成回调?

时间:2018-09-01 18:11:32

标签: vue.js vue-cli vue-cli-3

我想启动一个vue-cli dev服务器,然后在此构建完成后从节点运行命令。

是否可以从节点脚本运行vue-cli-service serve,以便一旦开发服务器启动并运行,我就可以收到回调?

1 个答案:

答案 0 :(得分:3)

vue-cli-service.js不返回服务承诺(这将允许您设置完成回调),但是您可以复制脚本(25行)来这样做:

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回调以在服务器成功启动时调用:

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');
  }
})

请确保更新package.json以使用新脚本:

package.json:

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