乐闻世界logo
搜索文章和话题

How to see Rust source code when debugging WebAssembly in a browser?

1个答案

1

When debugging WebAssembly compiled from Rust in a browser, you can follow these steps to view the Rust source code:

  1. Ensure source maps are included during compilation:

    When building your project with wasm-pack, use the --dev flag to include source maps. For example:

    sh
    wasm-pack build --dev

    If you build directly with cargo, ensure you use the --debug flag:

    sh
    cargo build --target wasm32-unknown-unknown --debug
  2. Generate source maps:

    Ensure source maps are generated for the .wasm file during compilation. Most Rust to WebAssembly toolchains automatically create these files.

  3. Include WebAssembly and source maps in your web project:

    Ensure both the .wasm file and the generated source maps are deployed to your web server and correctly referenced in your webpage.

  4. Configure Content-Type:

    Your web server must set the correct Content-Type header (application/wasm) for .wasm files to allow the browser to properly identify and load the WebAssembly module.

  5. Enable source code debugging in the browser:

    After loading your webpage, open the browser's developer tools:

    • Chrome: Press F12 or right-click on a page element and select 'Inspect', then switch to the 'Sources' tab.

    • Firefox: Press Ctrl+Shift+I (or Cmd+Option+I on 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.

  6. 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.

2024年6月29日 12:07 回复

你的答案