Using your library - Hello wasm-pack! (original) (raw)

  1. 1. Introduction
  2. 2. Quickstart
  3. 3. Prerequisites
    1. 3.1. npm (optional)
    2. 3.2. considerations
    3. 3.3. Non-rustup setups
  4. 4. Commands
    1. 4.1. new
    2. 4.2. build
    3. 4.3. test
    4. 4.4. pack and publish
    5. 4.5. init (DEPRECATED)
  5. 5. Tutorials
    1. 5.1. Hybrid applications with Webpack
      1. 5.1.1. Getting started
        1. 5.1.2. Using your library
    2. 5.2. npm browser packages
      1. 5.2.1. Getting started
          1. 5.2.1.1. Manual Setup
        1. 5.2.2. Template deep dive
          1. 5.2.2.1. Cargo.toml
            1. 5.2.2.2. src/lib.rs
            2. 5.2.2.3. src/utils.rs
            3. 5.2.2.4. wee_alloc
            4. 5.2.2.5. tests/web.rs
        2. 5.2.3. Building your project
        3. 5.2.4. Testing your project
        4. 5.2.5. Packaging and publishing
        5. 5.2.6. Using your library
  6. 6. Cargo.toml Configuration
  7. 7. Contributing

Hello wasm-pack!

Run The Code

The Rust Webpack template is designed for creating monorepo-style Web applications with Rust-generated WebAssembly and Webpack without publishing your wasm to NPM. This portion of the tutorial will explain how to build a Webpack JavaScript project that will run your WebAssembly code in the browser.

Scaffold a JavaScript Project

To generate a new Rust Webpack project, we've used the rust-webpack npm template.

npm init rust-webpack your-package-name

A new project folder will be created with the name you supply.

If we look in the project, we'll see the following:

The scaffolded project includes an example Rust WebAssembly webpack crate.

Inside the crate/src/lib.rs file we see a run function that's callable from our JS file:


# #![allow(unused_variables)]
#fn main() {
// Called by our JS entry point to run the example.
#[wasm_bindgen]
pub fn run() -> Result<(), JsValue> {
    set_panic_hook();

    // ...
    let p: web_sys::Node = document.create_element("p")?.into();
    p.set_text_content(Some("Hello from Rust, WebAssembly, and Webpack!"));
    // ...

    Ok(())
}
#}

Now, open up the js/index.js file. We see our Rust-generated wasm run function being called inside our JS file.

import("../crate/pkg").then(module => {
  module.run();
});

Run The Project

To generate our Rust-compiled to wasm code, in the root directory we run:

npm run build

This will create our bundled JavaScript module in a new directory dist.

We should be ready to run our project now! In the root directory, we'll run:

npm start

Then in a web browser navigate to http://localhost:8080 and you should be greeted with text in the body of the page that says "Hello from Rust, WebAssembly, and Webpack!"

If you did congrats! You've successfully used the rust-webpack template!