embed_js_build

Function postprocess_crate

Source
pub fn postprocess_crate(lib_name: &str, debug: bool) -> Result<PostProcessData>
Expand description

Call this once after a wasm-unknown-unknown build has completed (i.e. from a post-build script) in order to generate the javascript imports that should accompany the wasm binary.

See the embed_js repository for example projects using this function.

Parameters:

  • lib_name The binary name to process, typically the name of the crate unless set otherwise in Cargo.toml.
  • debug Whether to look for the debug or release binary to process. Until wasm32-unkown-unknown supports debug builds, this should always be set to false.

Example post-build script, taken from the “simple” example in the embed_js repository:

extern crate base64;
extern crate embed_js_build;

use std::fs::File;
use std::io::Write;

fn main() {
    let pp_data = embed_js_build::postprocess_crate("simple", false).unwrap();
    let in_base_64 = base64::encode(&pp_data.wasm);
    let html_path = pp_data.wasm_path.with_extension("html");
    let mut html_file = File::create(&html_path).unwrap();
    write!(html_file, r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> wasm test </title>
<script>
function _base64ToArrayBuffer(base64) {{
    var binary_string =  window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array( len );
    for (var i = 0; i < len; ++i) {{
        bytes[i] = binary_string.charCodeAt(i);
    }}
    return bytes.buffer;
}}
var bytes = _base64ToArrayBuffer(
"{}"
);
WebAssembly.instantiate(bytes, {{ env: {{
{}
}}}}).then(results => {{
    window.exports = results.instance.exports;
    console.log(results.instance.exports.add_two(2));
}});
</script>
</head>
</html>
"#,
           in_base_64,
           pp_data.imports
    ).unwrap();
}