Over the past few weeks, I was experimenting with ways to add debugging to my editor, and this post is an explanation of how to add custom debuggers to ReactNative. Our team is planning to add debugging to a bunch of other features that we plan to release as an extension for VSCode.
ReactNative Debugger today
Before writing a custom debugger, it is useful to appreciate how the existing setup works. I found an article that has an excellent explanation, though it is for an older version. The biggest change from the article is the use of a web worker in order to provide an isolated sandbox for the running scripts.
I created an "old-style" UML sequence diagram, hoping to capture most of the concepts without going too deep into the details.
The full SVG file may be easier to read. Most of the messages have a direct correspondence to methods in the source code.
Path to a Custom DebuggerWhen trying to implement a custom debugger, I considered the following approaches
- Create a parallel JSDebuggerWebSocketClient class to send messages to a process that I write, instead of sending it to the packager. While my process would have all the necessary debug hooks, I would still need to get source files and source maps from the packager.
Refining the debuggerSince the packager now proxies to the Node process instead of Chrome, some improvements are needed in the Node process
- In case of the Chrome debugger, ReactNative modules are loaded using the webworker construct - "importScripts". A Node process does not have a simple way to load scripts from a web server. Thus, we had to implement a way to download the code, and "require" it using runInNewContext. The sandboxed context also allows code isolation that the Webworker provides.
- Sourcemaps also have to be downloaded and changed so that they point to source files on the local system.
- For websockets capability in the node process, we could use the websocket npm module that provides an excellent, w3c compliant interface which could be used as a drop in replacement.
- Instead of requiring the user to shake the phone to enter into the debug mode, we could run
adb shell am broadcast -a "com.rnapp.RELOAD_APP_ACTION" --ez jsproxy=trueto enable proxy mode on the app.
Here is a pull request that looks at an environment variable and then launches a custom process, instead of defaulting to Chrome. This is similar to the way custom editors can be launched from ReactNative. I hope that the pull request is merged soon, so that custom debuggers can be added.
You can also signup for a preview. If you have additional feature requests or ideas that you think we should implement, please ping me and our team would love to talk to you.