<.> 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 bagrustc --version
Next, create a new Rust package:
This will generate the following folder structure:
cargo new rust-101 --lib
<项目>: 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
cargo install wasm-pack
<配>: Configure the dynamic library compatible with Webassembly.
<>: Enable communication between Rust and JavaScript.
wasm-bindgen
Cargo.toml
Installation dependencies:
[package] name = "rust-101" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2"
<.> 5. Update the rust code
crate-type = ["cdylib"]
function can be accessed from JavaScript: wasm-bindgen
cargo build
This command will:
src/lib.rs
Compile the Rust code to Webassembly. add
use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn add(left: u64, right: u64) -> u64 { left + right }
#[wasm_bindgen]
add
Create a
wasm-pack build --target web
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:
rustc --version
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!