[Vue CLI 3] 插件开辟之 registerCommand 究竟做了什么

起首,我们看到在 package.json 中有 scripts 的定义:

“scripts”: {
“serve”: “vue-cli-service serve”,
“build”: “vue-cli-service build”,
“lint”: “vue-cli-service lint”
}

我们看到 serve 和 build 实在多是依托的 vue-cli-service

之前我们提到过了经由过程 api.registerCommand 来注册敕令的:

比如在 cli-service/lib/commands/serve.js

module.exports = (api, options) => {
  api.registerCommand('serve', {
    // ...
  }, async function serve (args) {
  })
}

我们看一下 cli-service/lib/PluginAPI.js 文件:

class PluginAPI {
  constructor (id, service) {
    this.id = id
    this.service = service
  }
}

函数 registerCommand 会设置 service.commands

接收 3 个参数:

  • name
  • opts
  • fn
registerCommand (name, opts, fn) {
  if (typeof opts === 'function') {
    fn = opts
    opts = null
  }
  this.service.commands[name] = { fn, opts: opts || {}}
}

我们再看一下 cli-service/bin/vue-cli-service.js

service.run(command, args, rawArgv).catch(err => {
  error(err)
  process.exit(1)
})

cli-service/lib/Service.js 会挪用 run 要领:

async run (name, args = {}, rawArgv = []) {
}

内里会从 commands 内里取:

let command = this.commands[name]

终究实行它内里的 fn

const { fn } = command
return fn(args, rawArgv)
    原文作者:dailyvuejs
    原文地址: https://segmentfault.com/a/1190000016253182
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞