Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Use 'console.log' From WASM in Rust

This is how I'm calling out to console log from WASM Rust code. You don't really need to send the data in from the outside, but it shows that bridge as well which I find useful

Cargo.toml

[package]
name = "wasm_web_component"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = { version = "0.2.87" }
web-sys = { version = "0.3.64", features = ["console"]}

src/lib.rs

use wasm_bindgen::prelude::*;
use web_sys::console::log_1;

#[wasm_bindgen]
extern "C" {
    pub fn alert(s: &str);
}

#[wasm_bindgen]
pub fn log(msg: &str) {
    log_1(&msg.into());
}

- You have to open the index file through a server (e.g. browser - sync) for it to work. Otherwise you'll get a cors error.

- Building this is done with [TODO: Code shorthand span ] which can be installed with [TODO: Code shorthand span ]

- The build command is [TODO: Code shorthand span ]

- Webpack is not used in this approach

index.html

<!DOCTYPE html>
<html>
<body>
  <script type="module">
    import init, {log} from "./pkg/wasm_web_component.js";
    init().then(() => {
      log("ping test alfa");
    })
  </script>
</body>
</html>

Footnotes And References