react-source-locator-hyy
v0.0.1
Published
A source code locator tool with Babel plugin and dev server middleware
Downloads
201
Maintainers
Readme
Source Locator
一个用于快速定位 React 组件源码的开发工具包。通过 Ctrl/Cmd + 点击页面元素,即可在编辑器中打开对应的源码文件。
功能特性
- 🎯 精准定位:自动为 JSX 元素添加源码位置信息
- 🚀 快速跳转:Ctrl/Cmd + 点击即可在编辑器中打开源码
- 🔧 易于集成:提供 Babel 插件和 Webpack 中间件
- 🎨 编辑器支持:支持 VSCode、WebStorm、IDEA 等主流编辑器
安装
npm install react-source-locator-hyy --save-dev使用方法
1. 配置 Babel 插件
在你的 Babel 配置文件中添加插件:
babel.config.js
const { babelPlugin } = require("react-source-locator-hyy");
module.exports = {
plugins: [
// 只在开发环境启用
process.env.NODE_ENV === "development" && babelPlugin,
].filter(Boolean),
};或者在 webpack 配置中:
const { babelPlugin } = require("react-source-locator-hyy");
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
use: {
loader: "babel-loader",
options: {
plugins: [babelPlugin],
},
},
},
],
},
};2. 配置 DevServer 中间件
在 webpack 配置中添加中间件:
webpack.config.js
const { middleware } = require("react-source-locator-hyy");
module.exports = {
devServer: {
onBeforeSetupMiddleware: (devServer) => {
middleware(devServer, {
port: 8080,
editor: "vscode", // 或 'webstorm', 'idea'
});
},
},
};3. 在客户端启用定位功能
在你的应用入口文件中引入并启动:
src/index.js
import { devInspect } from "react-source-locator-hyy";
// 只在开发环境启用
if (process.env.NODE_ENV === "development") {
devInspect.run();
}或者使用自定义配置:
import { createInspector } from "react-source-locator-hyy";
const inspector = createInspector({
serverUrl: "http://localhost:8080",
endpoint: "/open-in-editor",
debug: true,
});
inspector.run();配置选项
Babel 插件
插件会根据以下环境变量自动启用:
NODE_ENV: 'development', 'dev', 'test'BUILD_ENV: 'development', 'dev', 'test'
DevServer 中间件
middleware(devServer, {
port: 8080, // 开发服务器端口
editor: "vscode", // 编辑器类型: 'vscode' | 'webstorm' | 'idea'
});客户端工具
createInspector({
serverUrl: "http://localhost:8080", // 开发服务器地址
endpoint: "/open-in-editor", // API 端点
debug: false, // 是否开启调试日志
});工作原理
- 构建时:Babel 插件为每个 JSX 元素添加
data-file和data-line属性 - 运行时:客户端监听 Ctrl/Cmd + 点击事件
- 定位:找到最近的带有源码位置信息的元素
- 跳转:发送请求到 DevServer,在编辑器中打开对应文件
示例
完整配置示例
webpack.config.js
const { middleware, babelPlugin } = require("react-source-locator-hyy");
module.exports = {
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: "babel-loader",
options: {
plugins: [babelPlugin],
},
},
},
],
},
devServer: {
port: 8080,
onBeforeSetupMiddleware: (devServer) => {
middleware(devServer, {
port: 8080,
editor: "vscode",
});
},
},
};src/index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { devInspect } from "react-source-locator-hyy";
// 启用源码定位
if (process.env.NODE_ENV === "development") {
devInspect.run();
}
ReactDOM.render(<App />, document.getElementById("root"));注意事项
- 此工具仅用于开发环境,请勿在生产环境使用
License
MIT
