文章目录
  1. 1. 安装Rust与Yew框架
  2. 2. 创建Rust项目,添加Yew依赖

Yew是rustlang语言中开发web应用的框架,定义组件的形式类似React。Yew中使用宏html!来定义html内容,Props传递组件参数,也有use_state等hook概念,如果熟悉React的话很容易上手。Yew会将html转换为rustlang代码,生成WebAssembly后在浏览器上执行。

Yew是一个挺有趣的框架, 不管目前是否可用于生产环境创建Web应用,至少可以学习了解下React中组件的概念在Rust语言中如何实现。

安装Rust与Yew框架

内容主要来自于Yew Tutorial https://yew.rs/docs/tutorial.

首先需要安装Rust开发工具, 参考https://www.rust-lang.org/tools/install。安装完成后,命令行里检查rustup与rustc的版本。

1
2
3
4
rustup -v
rustc --version
# 升级Rust工具请运行
rustup update

使用cargo安装trunk工具, 使用rustup安装Rust编译目标wasm32-unknown-unknown

1
2
cargo install trunk
rustup target add wasm32-unknown-unknown

创建Rust项目,添加Yew依赖

Rust中创建项目使用cargo命令,然后在Cargo.toml中添加依赖的库crate。

1
2
3
cargo new yew-app
cd yew-app
cargo run

编辑Cargo.toml文件,在依赖项[dependencies]下添加一行yew依赖, 这里直接指定git路径。

1
2
3
4
5
6
7
[package]
name = "yew-app"
version = "0.1.0"
edition = "2021"
[dependencies]
yew = { git = "https://github.com/yewstack/yew/", features = ["csr"] }

编辑src/main.rs, 将文件内容替换为如下内容. 可以看到在函数名app()上添加#[function_component(App)], 指定这是一个函数式组件, 组件名为App

1
2
3
4
5
6
7
8
9
10
11
12
use yew::prelude::*;
#[function_component(App)]
fn app() -> Html {
html! {
<h1>{ "Hello World" }</h1>
}
}
fn main() {
yew::Renderer::<App>::new().render();
}

然后在项目根目下创建index.html文件,内容如下:

1
2
3
4
5
<!doctype html>
<html lang="en">
<head></head>
<body></body>
</html>

至此,一个基础的Yew应用已经完成,可以启动应用,在浏览器中查看效果了。这里使用trunk命令,前面第一步时已经安装,它会自动将rust代码编译为webassembly, 并启动一个web服务器; 当代码有变更时,会自动重新编译。命令启动完成之后,浏览器打开http://localhost:8080查看。

1
trunk serve --open
文章目录
  1. 1. 安装Rust与Yew框架
  2. 2. 创建Rust项目,添加Yew依赖