用到的工具:react-dev-inspector
使用流程
根据react-dev-inspector文档进行配置
- 安装
yarn add --dev react-dev-inspector
- 配置:在根目录下配置Inspector
import { createRoot } from 'react-dom/client'
import { Inspector } from 'react-dev-inspector'
import { App } from './App'
import './index.css'createRoot(document.getElementById('root') as HTMLDivElement).render(<React.StrictMode><Inspector /><App /></React.StrictMode>,)
3. 我的工程是由create-react-app创建的,所以参考这部分文档,根据文档提示我需要先去安装customize-cra
4. 根据customize-cra文档进行配置
4.1 安装
npm i customize-cra react-app-rewired --dev
4.2 配置:新建config-overrides.js文件,需要与package.json文件同级
const {override,addDecoratorsLegacy,disableEsLint,addBundleVisualizer,addWebpackAlias,adjustWorkbox
} = require("customize-cra");
const path = require("path");module.exports = override(// enable legacy decorators babel pluginaddDecoratorsLegacy(),// disable eslint in webpackdisableEsLint(),// add webpack bundle visualizer if BUNDLE_VISUALIZE flag is enabledprocess.env.BUNDLE_VISUALIZE == 1 && addBundleVisualizer(),// add an alias for "ag-grid-react" importsaddWebpackAlias({["ag-grid-react$"]: path.resolve(__dirname, "src/shared/agGridWrapper.js")}),// adjust the underlying workboxadjustWorkbox(wb =>Object.assign(wb, {skipWaiting: true,exclude: (wb.exclude || []).concat("index.html")}))
);
- 回到react-dev-inspector文档,我们还需要安装配置一个中间件
5.1 安装
yarn add --dev @react-dev-inspector/middleware
5.2 配置:我们修改下4.2步中配置的config-overrides.js文件
const {override,overrideDevServer,addDecoratorsLegacy,disableEsLint,addBundleVisualizer,addWebpackAlias,adjustWorkbox,} = require("customize-cra");const { launchEditorMiddleware } = require('@react-dev-inspector/middleware')const path = require("path");const webapckOverride = override(// enable legacy decorators babel pluginaddDecoratorsLegacy(),// disable eslint in webpackdisableEsLint(),// add webpack bundle visualizer if BUNDLE_VISUALIZE flag is enabledprocess.env.BUNDLE_VISUALIZE == 1 && addBundleVisualizer(),// add an alias for "ag-grid-react" importsaddWebpackAlias({["ag-grid-react$"]: path.resolve(__dirname, "src/shared/agGridWrapper.js")}),// adjust the underlying workboxadjustWorkbox(wb =>Object.assign(wb, {skipWaiting: true,exclude: (wb.exclude || []).concat("index.html")})));module.exports = {/*** react-dev-inspector server config for webpack-dev-server*/devServer: overrideDevServer(serverConfig => {// https://webpack.js.org/configuration/dev-server/#devserversetupmiddlewaresserverConfig.setupMiddlewares = (middlewares) => {middlewares.unshift(launchEditorMiddleware)return middlewares}return serverConfig},),webpack: webapckOverride}
- 来到页面,按下快捷键
ctrl⌃ + shift⇧ + commmand⌘ + c(松开)
;鼠标移动到某个元素,并点击;就能看到编辑器打开了对应页面,且光标在该元素的位置
- 如果编辑器报错:
The editor process exited with an error: spawn code ENOENT
,可以参考从命令行启动
7.1在VS Code面板输入Cmd+Shift+P
7.2安装Shell command: Install 'code' command in PATH