如何本地 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 的两种方式,个人更倾向于第二种方式,编译源代码的方式稍微麻烦一些,但是对原始代码没有任何侵入性。

相关推荐
前端李易安36 分钟前
Web常见的攻击方式及防御方法
前端
PythonFun1 小时前
Python技巧:如何避免数据输入类型错误
前端·python
hakesashou1 小时前
python交互式命令时如何清除
java·前端·python
天涯学馆1 小时前
Next.js与NextAuth:身份验证实践
前端·javascript·next.js
HEX9CF1 小时前
【CTF Web】Pikachu xss之href输出 Writeup(GET请求+反射型XSS+javascript:伪协议绕过)
开发语言·前端·javascript·安全·网络安全·ecmascript·xss
ConardLi1 小时前
Chrome:新的滚动捕捉事件助你实现更丝滑的动画效果!
前端·javascript·浏览器
ConardLi2 小时前
安全赋值运算符,新的 JavaScript 提案让你告别 trycatch !
前端·javascript
凌云行者2 小时前
使用rust写一个Web服务器——单线程版本
服务器·前端·rust
华农第一蒟蒻2 小时前
Java中JWT(JSON Web Token)的运用
java·前端·spring boot·json·token
积水成江2 小时前
关于Generator,async 和 await的介绍
前端·javascript·vue.js