When debugging WebAssembly compiled from Rust in a browser, you can follow these steps to view the Rust source code:
-
Ensure source maps are included during compilation:
When building your project with
wasm-pack, use the--devflag to include source maps. For example:shwasm-pack build --devIf you build directly with
cargo, ensure you use the--debugflag:shcargo build --target wasm32-unknown-unknown --debug -
Generate source maps:
Ensure source maps are generated for the
.wasmfile during compilation. Most Rust to WebAssembly toolchains automatically create these files. -
Include WebAssembly and source maps in your web project:
Ensure both the
.wasmfile and the generated source maps are deployed to your web server and correctly referenced in your webpage. -
Configure Content-Type:
Your web server must set the correct
Content-Typeheader (application/wasm) for.wasmfiles to allow the browser to properly identify and load the WebAssembly module. -
Enable source code debugging in the browser:
After loading your webpage, open the browser's developer tools:
-
Chrome: Press
F12or right-click on a page element and select 'Inspect', then switch to the 'Sources' tab. -
Firefox: Press
Ctrl+Shift+I(orCmd+Option+Ion macOS) or right-click on a page element and select 'Inspect Element', then switch to the 'Debugger' tab.
In the developer tools' source panel, you should be able to see your Rust source files. If your WebAssembly and source maps are properly configured, these files will be loaded alongside your WebAssembly module.
-
-
Set breakpoints and debug:
Set breakpoints in the Rust source code. When the WebAssembly execution reaches these points, the browser will pause execution, allowing you to inspect the call stack, variables, and other information.
Note that different browsers and toolchains may vary, and these steps may differ based on the specific tools you use (such as wasm-bindgen, wasm-pack, or others) and your project setup. If you encounter any issues, consult the documentation for your specific tools to get environment-specific guidance.