
简介
当你刚上手新的 react 项目,启动后不知道网页中的内容对应代码中的哪里?项目添加 react-dev-inspector 插件吧!通过快捷键点击网页,直接跳转到编辑器中的代码位置!十分方便~
安装步骤
1. package.json 添加 devDependencies
npm i -D react-dev-inspector
2. babel 配置文件添加插件
// .babelrc.js
module.exports = {
plugins: [
/**
* react-dev-inspector plugin, options docs see:
* https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
*/
'react-dev-inspector/plugins/babel',
],
}
3. 修改 webpack 配置文件
有两种配置,配置其一即可,我用的是方法二的配置。
3.1 配置一:
// webpack.config.ts
import type { Configuration } from 'webpack'
import { ReactInspectorPlugin } from 'react-dev-inspector/plugins/webpack'
const config: Configuration = {
plugins: [
/**
* react-dev-inspector webpack plugin
* this plugin will create
* `devServer.setupMiddlewares` config for webpack5
* and `devServer.before` config for webpack4
*/
new ReactInspectorPlugin(),
],
}
3.2 配置二:
注:setupMiddlewares 需要 webpack-dev-server@4.7.0版本以上
setupMiddlewares 和 before 配置其一即可,根据对应的 create-react-app 或者 webpack-dev-server 版本配置。
// webpack.config.ts
import type { Configuration } from 'webpack'
import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'
const config: Configuration = {
devServer: {
/**
* react-dev-inspector - dev server config
* for create-react-app@^5 + webpack-dev-server@^4.7
*/
setupMiddlewares: (middlewares, devServer) => {
middlewares.unshift(launchEditorMiddleware)
return middlewares
},
/**
* react-dev-inspector - dev server config
* for create-react-app@^4 + webpack-dev-server@^3
*/
before: (app, server, compiler) => {
app.use(launchEditorMiddleware)
// ... other middlewares after
},
},
}
4. 创建一个 Wrapper 组件
示例:
import React from 'react';
import { Inspector, InspectParams } from 'react-dev-inspector';
const isDev = process.env.NODE_ENV === 'development';
interface IWrapperProps {
children: React.ReactElement;
}
function Wrapper(props: IWrapperProps) {
if (!isDev) return props.children;
return (
<Inspector
// props see docs:
// https://github.com/zthxxx/react-dev-inspector#inspector-component-props
keys={['control', 'shift', 'command', 'c']}
disableLaunchEditor={false}
onClickElement={({ codeInfo }: InspectParams) => {
if (!codeInfo?.absolutePath) return;
const { absolutePath, lineNumber, columnNumber } = codeInfo;
// you can change the url protocol if you are using in Web IDE
window.open(`vscode://file/${absolutePath}:${lineNumber}:${columnNumber}`);
}}>
{props.children}
</Inspector>
);
}
export default Wrapper;
5. 在项目中使用 Wrapper 组件
示例:
const app = (
<Wrapper>
<Router history={history}>
<YourComponent />
</Router>
</Wrapper>
);
ReactDOM.render(app, document.getElementById('app'));
6. 编辑器配置(重要!)
VSCode 快捷键
mac: cmd + shift + p
windows: ctrl + shift + p
打开后输入 shell command
选择 install 'code' command in PATH 即可
7. 尾言
配置了之后打开项目运行的网页,使用快捷键 ctrl + shift + cmd + c,然后点击指定区域就可以跳转到项目对应的代码处了!具体其他细节请看官方 Github 。