如何本地 Debug React 源码

日常开发过程中,有时 debug react 源代码进行问题排查。一种方案是直接把通过 html 引入进来,另外一种是编译并通过 yarn 链接到项目中,本地将介绍如何通过这两种方法进行代码 Debug。

页面引入源代码方式

这种方式比较简单,直接引入 React 代码,适合学习使用。

复制代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      const { useState } = React;
      
      function MyApp() {
        const [counter, setCounter] = useState(10)       
        return <h1>Hello, world! </h1>;
      }

      const container = document.getElementById('root');
      const root = ReactDOM.createRoot(container);
      root.render(<MyApp />);

    
    </script>
    <!--
      Note: this page is a great way to try React but it's not suitable for production.
      It slowly compiles JSX with Babel in the browser and uses a large development build of React.

      Read this page for starting a new React project with JSX:
      https://react.dev/learn/start-a-new-react-project

      Read this page for adding React with JSX to an existing project:
      https://react.dev/learn/add-react-to-an-existing-project
    -->
  </body>
</html>

找到想要 debug 的代码,添加断点进行 debug。

编译源代码

通过编译源代码进行React的 Debug,这种方式的好处是可以直接在项目中使用,替换项目引用的 React。

  1. 从 github 下载最新代码,并指定所需要的版本

    git clone https://github.com/facebook/react

    查询分支

    git brank -r

    checkout想要的版本号

    git checkout ${version}

  2. 安装依赖

    yarn install

  3. React 使用 yarn workspace 进行多项目管理,由于测试项目为web 项目,只需编译React和React-Dom。

    yarn build react/index,react/jsx,react-dom/index,scheduler --type=NODE

  4. 进入编译好的项目目录并创建 link,替换项目使用 React 和 React-Dom

    react link

    build/node_modules/react
    yarn link

    react-dom link

    build/node_modules/react-dom
    yarn link

  5. 进入当前项目目录,这里通过 CRA 创建了一个新项目

    create project

    npx create-react-app react-client

    进入项目目录运行

    cd react-client
    yarn link react react-dom

可以看到 react 和 react-dom 都已经地换成为软连接的形式

  1. 启动项目,找到需要 debug 方法添加断点即可

    yarn start

总结

对于React 代码 debug 的两种方式,个人更倾向于第二种方式,编译源代码的方式稍微麻烦一些,但是对原始代码没有任何侵入性。

相关推荐
mCell2 小时前
AI 时代 SVG 画图的潜力
前端·agent·svg
我命由我123458 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
Hopebearer_9 小时前
页面突然只剩 DOM?一次静态资源版本错配排查
前端·部署
抱抱宝9 小时前
Agent-study项目教程(03):手写 Mini-ReAct Agent(不依赖框架)
javascript·人工智能·gpt·react.js·prompt·agent
东风破_9 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
圣殿骑士-Khtangc11 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
BigTopOne11 小时前
【ijkplayer】 硬解码流程
前端
kyriewen12 小时前
DeepSeek Harness开源第一天我就上手了——和Claude Code的差距比想象中大
前端·ai编程·deepseek
捡田螺的小男孩12 小时前
什么是 Skill?手把手带你写一个简单有用的 Skill!
前端·后端·程序员
IT_陈寒12 小时前
Redis集群这个坑,差点让我通宵
前端·人工智能·后端