From Wasm by Example - Importing Javascript Functions Into WebAssembly.


Rust module:

// The wasm-pack uses wasm-bindgen to build and generate JavaScript binding file.
// Import the wasm-bindgen crate.
use wasm_bindgen::prelude::*;

// Let's define our external function (imported from JS)
// Here, we will define our external `console.log`
#[wasm_bindgen]
extern "C" {
    // Use `js_namespace` here to bind `console.log(..)` instead of just
    // `log(..)`
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}

// Export a function that will be called in JavaScript
// but call the "imported" console.log.
#[wasm_bindgen]
pub fn console_log_from_wasm() {
    log("This console.log is from wasm!");
}

TypeScript calling compiled wasm module:

import wasmInit from "wasm-concepts-import-js-functions";

const runWasm = async () => {
  // Instantiate our wasm module
  const rustWasm = await wasmInit();

  // Run the exported function
  rustWasm.console_log_from_wasm(); // Should log "This console.log is from wasm!"
};
runWasm();

Imported onto page, see browser console!