react-dev-inspector使用指南(踩坑)

5,799 阅读2分钟

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())
    },
  },

react运行时

动图中显示的页面需要有遮罩层,所以需要运行时代码

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
      // props docs see below
      keys={['control', 'shift', 'command', 'c']}
      disableLaunchEditor={false}
      onHoverElement={(params: InspectParams) => {}}
      onClickElement={(params: InspectParams) => {}}
    >
     <YourComponent>
       ...
     </YourComponent>
    </InspectorWrapper>
  )
}

配置编辑器

这个时候还不足以打开编辑器并定位到具体的位置,因为在环境中还不能调动编辑器,在vscode中做如下操作即可。

  1. 打开vscode
  2. ctrl + shift + p,输入shell command

选择install 'code' command in PATH 即可

you can use window.__REACT_DEV_INSPECTOR_TOGGLE__() to toggle inspector. 你也可以使用该方法切换调试模式