背景
在平时的开发中,疾速定位需要所在的代码文件
,是非常常见的需要。
一般来说,常见的定位源码的形式有:
搜寻页面关键字
页面路由
Devtool 中的组件名
- 好的记忆力
这些形式往往效率都不是很高,而且可能须要很长的操作门路能力达到目标, 比拟麻烦。
如果通过点击页面,能间接关上代码所在的文件, 岂不是美滋滋 ?
明天咱们就来探索一下:如何实现一键跳转
。
明天的次要内容:
React 我的项目该如何配置
Vue 我的项目该如何配置
相干原理探索
注释
React 我的项目该如何配置
对于 React 我的项目,有这样一个款插件: react-dev-inspector
。
它的神奇之处就在于:
能够从页面上辨认 react 组件,间接跳转到本地 IDE 的代码片段上。
1. 装置
npm i -D react-dev-inspector
2. 引入到对应的组件中
import React from 'react'import { Inspector, InspectParams } from 'react-dev-inspector'const InspectorWrapper = process.env.NODE_ENV === 'development' ? Inspector : React.Fragmentexport const Layout = () => { // ... return ( <InspectorWrapper keys={['control', 'shift', 'command', 'c']} disableLaunchEditor={false} onHoverElement={(params: InspectParams) => {}} onClickElement={(params: InspectParams) => {}} > <YourComponent> // ... </YourComponent> </InspectorWrapper> )}
babel 配置
// babelrc.jsexport default { plugins: [ 'react-dev-inspector/plugins/babel', ],}
webpack 配置
// webpack.config.tsimport type { Configuration } from 'webpack'import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'const config: Configuration = { devServer: { before: (app) => { app.use(launchEditorMiddleware) }, },}
另外, 这个插件也反对 Vite:
// 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 我的项目该如何配置
Vue Devtools
在 4.0
版本之后, 也提供了一个这样的性能:
一键在编辑器中关上组件的源码文件
。
实现以上 devtool 的性能配置, 只须要简略的三步:
1. 装置 launch-editor-middleware
npm i -D launch-editor-middleware
2. 更改webpack devServer配置
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/...
3. 把编辑器的门路退出到环境变量PATH中
抉择 install 'code' command in PATH
即可.
相干原理探索
篇幅无限,为了更好的浏览体验,具体原理能够参考如下文章:
我点了页面上的元素,VSCode 乖乖关上了对应的组件?原理揭秘。
https://juejin.cn/post/690146...
最初
疾速定位到代码所在位置,肯定水平上能进步咱们的开发效率,专一在更有价值的事件上。