您的位置:首页 > 文旅 > 美景 > 如何本地 Debug React 源码

如何本地 Debug React 源码

2024/7/6 21:13:45 来源:https://blog.csdn.net/hawk2014bj/article/details/139265632  浏览:    关键词:如何本地 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-projectRead 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 的两种方式,个人更倾向于第二种方式,编译源代码的方式稍微麻烦一些,但是对原始代码没有任何侵入性。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com