使用Yew 创建一个简单的WebAssembly 项目

368 阅读1分钟

Yew 简介

  • Rust 多线程的 WebAssembly 前端框架。
  • 官网;yew.rs/

环境配置

  1. vs code 安装 rust-analyzerBetter TOMLcratesCodeLLDB 插件。
  2. 根据官网安装 Rust:www.rust-lang.org/zh-CN/tools…
  3. 安装 WebAssembly target:rustup target add wasm32-unknown-unknown
  4. 安装 Trunk: cargo install trunk

创建一个简单的 Yew app

  1. cargo new yew-app -> cd yew-app

  2. 在 Cargo.toml 中添加 Yew 依赖。

     [dependencies]
     # you can check the latest version here: https://crates.io/crates/yew
     yew = "0.19"
    
  3. 在项目根目录下添加 index.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Yew App</title>
      </head>
    </html>
    
  4. 更新 main.rs

    use yew::prelude::\*;
    
        #[function_component(App)]
        fn app() -> Html {
            html!(<div>{"Hello, world!"}</div>)
        }
    
        fn main() {
            yew::start_app::<App>();
        }
    
    
    
  5. 运行 trunk serve -> 打开浏览器,可以看到 Hello, world!。 至此一个简单的 Yew app 就完成了。

下篇: Yew app 在浏览器控制台打印 console.log