1. 程式人生 > >[Vue CLI 3] 外掛開發之 registerCommand 到底做了什麼

[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)

來源:https://segmentfault.com/a/1190000016253182