To build a WebAssembly application with Rust, you will need to set up your development environment, create a new Rust project, and compile it to WebAssembly. We will also cover how to integrate it with HTML and JavaScript to create a functional web application.

Prerequisites

Before you start, ensure you have the following installed:

  • Rust (including cargo)
  • wasm-pack
  • A modern web browser (Chrome, Firefox, etc.)
  • Node.js (optional, for serving the application)

Setting Up Your Rust Project

  1. Create a new Rust project:

Open your terminal and run the following command:

   cargo new wasm_example --lib
   cd wasm_example

This creates a new library project named wasm_example.

  1. Update Cargo.toml:

Open the Cargo.toml file and add the following dependencies:

   [lib]
   crate-type = ["cdylib"]

   [dependencies]
   wasm-bindgen = "0.2"

The cdylib crate type allows Rust to compile to a dynamic library suitable for WebAssembly. The wasm-bindgen crate facilitates communication between Rust and JavaScript.

  1. Write Your Rust Code:

Open src/lib.rs and replace its contents with the following code:

   use wasm_bindgen::prelude::*;

   #[wasm_bindgen]
   pub fn greet(name: &str) -> String {
       format!("Hello, {}!", name)
   }

This simple function takes a string input and returns a greeting.

Compiling to WebAssembly

  1. Compile the Rust code:

In your terminal, run:

   wasm-pack build --target web

This command compiles your Rust code to WebAssembly and generates the necessary JavaScript bindings.

  1. Directory Structure:

After building, you will see a new directory named pkg containing your compiled .wasm file and a JavaScript wrapper.

Integrating with HTML and JavaScript

  1. Create an HTML file:

In your project root, create an index.html file with the following content:

   <!DOCTYPE html>
   <html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Wasm Example</title>
   </head>
   <body>
       <h1>WebAssembly with Rust</h1>
       <input id="name" type="text" placeholder="Enter your name">
       <button id="greet-button">Greet</button>
       <p id="greeting"></p>

       <script type="module">
           import init, { greet } from './pkg/wasm_example.js';

           async function run() {
               await init();
               const button = document.getElementById('greet-button');
               button.onclick = () => {
                   const name = document.getElementById('name').value;
                   const greeting = greet(name);
                   document.getElementById('greeting').innerText = greeting;
               };
           }

           run();
       </script>
   </body>
   </html>

This HTML file sets up a simple user interface where users can enter their name and receive a greeting.

Serving Your Application

To serve your application, you can use a simple HTTP server. If you have Node.js installed, you can use the http-server package:

  1. Install http-server:
   npm install -g http-server
  1. Run the server:

In your terminal, run:

   http-server .

This command serves your current directory at http://localhost:8080. Open this URL in your web browser.

Best Practices

  • Error Handling: Always handle potential errors in your Rust code. Use the Result type to manage errors gracefully.
  • Performance: Minimize the size of your WebAssembly binary by optimizing your Rust code. Use the --release flag when building for production.
  • Modular Code: Organize your Rust code into modules to improve readability and maintainability.
  • Testing: Write tests for your Rust code using the built-in testing framework. Run tests with cargo test.

Conclusion

You have now built a simple WebAssembly application using Rust. This tutorial covered the essential steps from setting up your environment to integrating Rust with HTML and JavaScript. By following best practices, you can create efficient and maintainable WebAssembly applications.


Learn more with useful resources