preamble
WebAssembly (WASM) has become a powerful tool in modern web development. It allows developers to run high-performance code in the browser, crossing the traditional performance limitations of JavaScript. the Rust language has become a popular choice for writing WASM modules because of its efficiency and memory safety. This article describes how to compile Rust code into WebAssembly and use it in a web project.
1. Create a Rust project
First, we need to create a new Rust project. Since we want to generate a module that can be called by other languages or tools, we chose to create a library project instead of an executable program. Use thecargo
command can be done easily:
cargo new lib_wasm --lib
This command generates a file namedlib_wasm
project, which contains a base configuration file and a
src/
file in which you will write your Rust code.
2. Addwasm-bindgen
dependency
In Rust, thewasm-bindgen
is a key tool that makes the interaction between Rust and JavaScript much easier.wasm-bindgen
Responsible for generating the binding code needed to interact with JavaScript, allowing you to call functions written in Rust directly.
To addwasm-bindgen
You can use thecargo add
Command:
cargo add wasm-bindgen
Alternatively, manually edit the file, add the following dependencies:
[dependencies]
wasm-bindgen = "0.2"
increasewasm-bindgen
After that, the Rust compiler generates the necessary binding files during compilation so that your WASM module can be called directly by JavaScript.
3. Installationwasm32-unknown-unknown
goal
By default, the Rust compiler generates executables for the native machine architecture. To compile into a WebAssembly file for the Web, we need to add a specific target architecture, thewasm32-unknown-unknown
This is a generic WASM target that does not depend on any specific operating system. This is a generic WASM target that does not depend on any specific operating system.
Use the following command to install the target:
rustup target add wasm32-unknown-unknown
This command configures your Rust toolchain to generate binaries for WebAssembly.
4. Writing Rust code
Now, you can find out more about this in thesrc/
file to write the function you wish to export. For example, we can write a simple function that takes a name as an argument and returns a greeting:
use wasm_bindgen::prelude::*;
// utilization #[wasm_bindgen] macro to export a function to the JavaScript
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
In this code, we use the#[wasm_bindgen]
magnificentgreet
function is exported so that it can be called from JavaScript.
5. Compile the Rust project as WASM
After writing the code, we can compile it into a WASM file. When compiling, specify the target aswasm32-unknown-unknown
and use--release
option generates an optimized build:
cargo build --target wasm32-unknown-unknown --release
After the compilation is complete, the resulting.wasm
The file will be stored in thetarget/wasm32-unknown-unknown/release/
Catalog.
6. Utilizationwasm-bindgen
Generate JavaScript Binding Code
Although the compilation generates.wasm
file, but it's not convenient to use it directly in JavaScript. To do this, we need to use thewasm-bindgen
tool generates the appropriate JavaScript binding code. This creates a module that is easy to call in JavaScript.
First, make sure you have installedwasm-bindgen-cli
Tool. You can install it with the following command:
cargo install wasm-bindgen-cli
Then, run the following command to generate the JavaScript binding file:
wasm-bindgen --out-dir ./out --target web target/wasm32-unknown-unknown/release/lib_wasm.wasm
This will be in theout
The directory generates a series of files, including.js
documents and.wasm
file that you can use directly in your Web projects.
7. Use of the WASM module in web pages
The generated WASM module is now ready to be used in a web project. All you need to do is import the generated JavaScript bindings into an HTML file and call the functions exported by Rust. For example:
<!DOCTYPE html>
<html>
<head>
<title>Lib WASM Demo</title>
</head>
<body>
<script type="module">
import init, { greet } from "./out/lib_wasm.js";
init().then(() => {
(greet("World"));
});
</script>
</body>
</html>
This example will print out "Hello, World!" on the console. whereinit
function is used to initialize the WASM module, while thegreet
function calls the function we defined in Rust.
The web project directory structure is as follows:
out/
├── lib_wasm_bg.wasm
├── lib_wasm_bg.
├── lib_wasm.
└── lib_wasm.js
out
directory contains the generated WASM files and the corresponding JavaScript bindings. is a simple web page for testing and presenting your WASM module.
concluding remarks
This process makes it easy to compile Rust code into WebAssembly and integrate it into your web projects.The combination of Rust's efficiency and WebAssembly's flexibility can bring significant performance gains to web applications.