在平时的开发中,快速定位需求所在的代码文件
,是十分常见的需求。react
通常来讲,常见的定位源码的方式有:webpack
搜索页面关键字
页面路由
Devtool 中的组件名
这些方式每每效率都不是很高,并且可能须要很长的操做路径才能达到目的, 比较麻烦。git
若是经过点击页面,能直接打开代码所在的文件, 岂不是美滋滋 ?
今天咱们就来探究一下:如何实现一键跳转
。github
今天的主要内容:web
React 项目该如何配置
Vue 项目该如何配置
相关原理探究
对于 React 项目,有这样一个款插件: react-dev-inspector
。shell
它的神奇之处就在于: npm
能够从页面上识别 react 组件,直接跳转到本地 IDE 的代码片断上。babel
npm i -D react-dev-inspector
import React from 'react' import { Inspector, InspectParams } from 'react-dev-inspector' const InspectorWrapper = process.env.NODE_ENV === 'development' ? Inspector : React.Fragment export const Layout = () => { // ... return ( <InspectorWrapper keys={['control', 'shift', 'command', 'c']} disableLaunchEditor={false} onHoverElement={(params: InspectParams) => {}} onClickElement={(params: InspectParams) => {}} > <YourComponent> // ... </YourComponent> </InspectorWrapper> ) }
// babelrc.js export default { plugins: [ 'react-dev-inspector/plugins/babel', ], }
// webpack.config.ts import type { Configuration } from 'webpack' import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack' const config: Configuration = { devServer: { before: (app) => { app.use(launchEditorMiddleware) }, }, }
另外, 这个插件也支持 Vite:app
// vite.config.ts: import { defineConfig } from 'vite' import { inspectorServer } from 'react-dev-inspector/plugins/vite' export default defineConfig({ plugins: [ inspectorServer(), ], })
这个时候还不足以打开编辑器并定位到具体的位置,由于在环境中还不能调动编辑器,在 vs code 中作以下操做便可。编辑器
vscode
ctrl + shift + p
,输入shell command
:选择 install 'code' command in PATH
便可.
you can use window.__REACT_DEV_INSPECTOR_TOGGLE__() to toggle inspector. 也可使用该方法切换调试模式。
更多配置信息能够参考: https://github.com/zthxxx/rea...
Vue Devtools
在 4.0
版本以后, 也提供了一个这样的功能:
一键在编辑器中打开组件的源码文件
。
实现以上 devtool 的功能配置, 只须要简单的三步:
npm i -D launch-editor-middleware
const openInEditor = require('launch-editor-middleware'); module.exports = { devServer: { before: (app) { app.use('/__open-in-editor', openInEditor('code')); } } }
在before
方法中,给devServer
注册一个/__open-in-editor
的 HTTP 路由,并在路由的回调中经过launch-editor-middleware
唤起编辑器。
openInEditor
方法的参数, code
表示编辑器是 VS Code。
更多支持的编辑器和参数能够参考:https://github.com/yyx990803/...
选择 install 'code' command in PATH
便可.
篇幅有限,为了更好的阅读体验,具体原理能够参考以下文章:
🎉我点了页面上的元素,VSCode 乖乖打开了对应的组件?原理揭秘。
https://juejin.cn/post/690146...
快速定位到代码所在位置,必定程度上能提升咱们的开发效率,专一在更有价值的事情上。