Skip to content

support building binary crates #734

Open
@boringcactus

Description

@boringcactus

💡 Feature description

Using wasm-pack to build libraries is nice, but binaries are also good to have, both in the npm ecosystem and for browser usage (see also rustwasm/wasm-bindgen#1630 and rust-gamedev/wg#51). However, wasm-pack asserts in a few places that all crates being built are libraries.

💻 Basic example

A crate with the following code in src/main.rs should build and run as intended with wasm-pack build --target web:

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

#[cfg(target_arch = "wasm32")]
fn display(text: &str) {
    // Use `web_sys`'s global `window` function to get a handle on the global
    // window object.
    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    let body = document.body().expect("document should have a body");

    // Manufacture the element we're gonna append
    let val = document.create_element("p").expect("failed to create a <p>");
    val.set_inner_html(text);

    body.append_child(&val).expect("failed to append child to body");
}

#[cfg(not(target_arch = "wasm32"))]
fn display(text: &str) {
    println!("{}", text);
}

fn main() {
    display("Hello from Rust!");
}

(I've made the changes needed in wasm-bindgen already; they're included in v0.2.54. I have a basic implementation for this feature already, but it needs additional tuning to behave as expected in all cases.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions