如何本地 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} 
  1. 安装依赖
yarn install 
  1. React 使用 yarn workspace 进行多项目管理,由于测试项目为web 项目,只需编译React和React-Dom。
yarn build react/index,react/jsx,react-dom/index,scheduler --type=NODE
  1. 进入编译好的项目目录并创建 link,替换项目使用 React 和 React-Dom
## react link
build/node_modules/react 
yarn link

## react-dom link
build/node_modules/react-dom
yarn link
  1. 进入当前项目目录,这里通过 CRA 创建了一个新项目
# create project
npx create-react-app react-client
# 进入项目目录运行
cd react-client
yarn link react react-dom

在这里插入图片描述
可以看到 react 和 react-dom 都已经地换成为软连接的形式
在这里插入图片描述
6. 启动项目,找到需要 debug 方法添加断点即可

yarn start

在这里插入图片描述

总结

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

  • 16
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值