react项目中有这样一个款插件react-dev-inspector
,用来解决什么问题呢?
就是当一个已经上线的项目出现了一个bug的时候,如果你对该项目不是非常熟悉,那么你就需要从来去捋一遍代码,还要非常费劲的去找到该处的代码位置,那么react-dev-inspector
就是来解决这个问题的。借用github的一张动图来表示,如下:
一、配置loader
在webpack中配置loader的作用是,在打包的过程中获取代码的位置,并记录在元素的html属性上,基本上有这么几个内容:代码的文件位置,代码的行数,代码的列数生成的元素如下结构如下:
<div
data-inspector-line="11"
data-inspector-column="4"
data-inspector-relative-path="src/components/Slogan/Slogan.tsx"
class="css-1f15bld-Description e1vquvfb0"
>
<p data-inspector-line="44" data-inspector-column="10" data-inspector-relative-path="src/layouts/index.tsx" > Inspect react components and click will jump to local IDE to view component code. </p>
</div>;
在webpack中具体配置如下:
module: {
rules: [
{
test: /\.[jt]sx$/,
exclude: [
/node_modules/,
/file-you-want-exclude/,
],
use: [
{
loader: 'react-dev-inspector/plugins/webpack/inspector-loader',
options: [{
// loader options type and docs see below
exclude: [
'xxx-file-will-be-exclude',
/regexp-to-match-file /,
],
babelPlugins: [],
babelOptions: {},
}],
},
],
},
],
},
一定要注意:
这里有一个坑点,就是该项功能使用的是
AST
,所以该loader
应该配置在babel-loader
的后边,也就是说需要被babel-loader
编译成AST
之后,才可以被该loader
识别并转换。
二、配置plugins
上边获取的仅仅是该代码的相对位置,还需要拿到绝对路径,这里需要把该项目的工作目录配置好,如下:
import { DefinePlugin } from 'webpack'
plugins: [
new DefinePlugin({
'process.env.PWD': JSON.stringify(process.cwd()),
}),
]
配置webpackDevServer
需要在本地监听是否点击了相关组件,在服务端就会打开代码位置
import { createLaunchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'
devServer: {
before: (app) => {
app.use(createLaunchEditorMiddleware())
},
},
三、在根组件配置 inSpectorWrapper
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>
)
}
四、配置编辑器
这个时候还不足以打开编辑器并定位到具体的位置,因为在环境中还不能调动编辑器,在vscode
中做如下操作即可。
- 打开vscode
- 按
ctrl + shift + p
,输入shell command
选择install 'code' command in PATH
即可
you can use window.__REACT_DEV_INSPECTOR_TOGGLE__() to toggle inspector.
你也可以使用该方法切换调试模式