Rust: Convert an existing project to compile to WASM

  • Add to Cargo.toml:

    [lib]
    crate-type = ["cdylib", "rlib"]
    
  • Also add this dependency:

    wasm-bindgen = "0.2"
    
  • Annotate public structs/functions with #[wasm_bindgen]

  • Set up console_error_panic_hook to improve error messages:

    console_error_panic_hook = "0.1.6"
    
    #[wasm_bindgen]
    pub fn set_panic_hook() {
        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();
    }
    
    set_panic_hook();
    
  • Import these (not very well documented) chrono features if necessary:

    chrono = { version = "0.4.11", features = ["wasmbind", "js-sys"] }
    
  • And build as usual:

    $ wasm-pack build --target web
    
Edit