In this tutorial, we will learn how to run the RUST application in the web browser. We will create a simple Rust package, compile it to Webassembly (WASM), and integrate it into a HTML page.
<.> 1. Install Rust
First of all, you need to install Rust. Please refer to Rust's official installation guide:
Rust installation guide. After the installation is completed, run the following command to verify whether the installation is successful:
<.> 2. Create a rust bag<code class="language-bash">rustc --version</code>
Next, create a new Rust package:
This will generate the following folder structure:
<code class="language-bash">cargo new rust-101 --lib</code>
: The configuration file of the project is similar to
<code>├── Cargo.toml └── src └── lib.rs</code>
Cargo.toml
package.json
lib.rs
lib.rs
To run the Rust code on the web, you need to compile it to Webassembly (WASM). For this, install Tools: add
<.> 4. Create communication between Rust and JavaScript
In order to connect Rust and JavaScript, we will use Crate. Update The file is as follows: wasm-pack
<code class="language-bash">cargo install wasm-pack</code>
: Configure the dynamic library compatible with Webassembly.
: Enable communication between Rust and JavaScript.
wasm-bindgen
Cargo.toml
Installation dependencies:
<code class="language-toml">[package] name = "rust-101" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2"</code>
<.> 5. Update the rust code
crate-type = ["cdylib"]
function can be accessed from JavaScript: wasm-bindgen
<code class="language-bash">cargo build</code>
This command will:
src/lib.rs
Compile the Rust code to Webassembly. add
<code class="language-rust">use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn add(left: u64, right: u64) -> u64 { left + right }</code>
#[wasm_bindgen]
add
Create a
<code class="language-bash">wasm-pack build --target web</code>
pkg/
<.> 8. Start the web page
To run the webpage, you need to use a local web server to provide services. You can use any web server you like, such as Live Server Extension (VS Code). in the browser console (Ctrl Shift J or CMD Option J), you should see:
<code class="language-bash">rustc --version</code>
That's it! I hope this tutorial will help you. Please share your feedback or questions at any time!
Reference:
The above is the detailed content of How to Run a Rust Application in the Web. For more information, please follow other related articles on the PHP Chinese website!