前言
研究windows环境下,vue-devtools与编辑器通信原理
什么是vue-devtools?
vue-devtools是一款基于chrome游览器的插件,用于调试vue应用
如何使用?
![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 监听请求
//node_modules\@vue\cli-service\lib\commands\serve.js
app.use('/__open-in-editor', launchEditorMiddleware())
因为 vue-devtools 在Vue CLI 3中是开箱即用,所以vue cli 在启动时会开启一个node服务,并且监听 /__open-in-editor 路径,如果有请求访问则调用 launchEditorMiddleware 中间件
3.launchEditorMiddleware
//node_modules\launch-editor-middleware\index.js
const launch = require('launch-editor')
module.exports = (specifiedEditor, srcRoot, onErrorCallback) => {
return function launchEditorMiddleware (req, res, next) {
const { file } = url.parse(req.url, true).query || {}
if (!file) {
res.statusCode = 500
res.end(`launch-editor-middleware: required query param "file" is missing.`)
} else {
launch(path.resolve(srcRoot, file), specifiedEditor, onErrorCallback)
res.end()
}
}
}
这里主要是在项目目录中,查找请求所携带参数文件路径,如果无法在项目目录中找到对应文件就提示错误,可以找到的话,调用launch-editor
4.launch-editor
//node_modules\launch-editor\index.js
function launchEditor (file, specifiedEditor, onErrorCallback) {
// 省略 ...
if (process.platform === 'win32') {
/*
editor => "H:\\Microsoft VS Code\\Code.exe"
args => "项目路径\\src\\components\\HelloWorld.vue"
*/
_childProcess = childProcess.spawn(
'cmd.exe',
['/C', editor].concat(args),
{ stdio: 'inherit' }
)
}
// 省略 ...
}
使用 child_process执行命令,这里的语句相当于执行 code “项目路径\src\components\HelloWorld.vue”