前言

研究windows环境下,vue-devtools与编辑器通信原理

什么是vue-devtools?

vue-devtools是一款基于chrome游览器的插件,用于调试vue应用

如何使用?

RI`KH0R5]{UK5(VZ1MC3YE1.png
![P{9HA(ZL6U}}KYC)FWN}L3.png

原理及执行过程

1.浏览器发起请求

点击 vue-devtools 按钮(open in editor ),发起请求http://localhost:8080/__open-in-editor?file=src/components/HelloWorld.vue

2.vue cli 监听请求

  1. //node_modules\@vue\cli-service\lib\commands\serve.js
  2. app.use('/__open-in-editor', launchEditorMiddleware())

因为 vue-devtools 在Vue CLI 3中是开箱即用,所以vue cli 在启动时会开启一个node服务,并且监听 /__open-in-editor 路径,如果有请求访问则调用 launchEditorMiddleware 中间件

3.launchEditorMiddleware

  1. //node_modules\launch-editor-middleware\index.js
  2. const launch = require('launch-editor')
  3. module.exports = (specifiedEditor, srcRoot, onErrorCallback) => {
  4. return function launchEditorMiddleware (req, res, next) {
  5. const { file } = url.parse(req.url, true).query || {}
  6. if (!file) {
  7. res.statusCode = 500
  8. res.end(`launch-editor-middleware: required query param "file" is missing.`)
  9. } else {
  10. launch(path.resolve(srcRoot, file), specifiedEditor, onErrorCallback)
  11. res.end()
  12. }
  13. }
  14. }

这里主要是在项目目录中,查找请求所携带参数文件路径,如果无法在项目目录中找到对应文件就提示错误,可以找到的话,调用launch-editor

4.launch-editor

  1. //node_modules\launch-editor\index.js
  2. function launchEditor (file, specifiedEditor, onErrorCallback) {
  3. // 省略 ...
  4. if (process.platform === 'win32') {
  5. /*
  6. editor => "H:\\Microsoft VS Code\\Code.exe"
  7. args => "项目路径\\src\\components\\HelloWorld.vue"
  8. */
  9. _childProcess = childProcess.spawn(
  10. 'cmd.exe',
  11. ['/C', editor].concat(args),
  12. { stdio: 'inherit' }
  13. )
  14. }
  15. // 省略 ...
  16. }

使用 child_process执行命令,这里的语句相当于执行 code “项目路径\src\components\HelloWorld.vue”

参考: