Ccmmutty logo
Commutty IT
4 min read

rustでtodoアプリを作ってみる①〜Hello Worldの表示まで〜

https://cdn.magicode.io/media/notebox/blob_N19oz0B

はじめに

rustを使用してTodoアプリを作っていきたいと思います。
以下のサイトを参考にさせていただきました。 https://zenn.dev/azukiazusa/articles/rust-base-web-front-fremework-yew
というか、エラーの対処を含めて自分の備忘録的に書いているので上記で作成できるならこの記事は見る必要ないかなーと思います。

環境

  • rustc 1.60.0
  • rustup 1.24.3
  • cargo 1.60.0

準備

とりあえずまずはrustをアップデート
Terminal
% rustup update
Cargoを使ってtrunkをインストール
Terminal
% cargo install trunk
WASMのターゲットを指定
Terminal
% rustup target add wasm32-unknown-unknown

プロジェクトの作成

Cargoのプロジェクトを作成する。
Terminal
% cargo new todo-app
プロジェクトが作成されていることを確認するためにcargo runを実行して確認する。 cd コマンドでtodo-appのディレクトリまで移動して以下を実行。
Terminal
% cargo run
実行結果:Hello, world!が表示されればOK。
Compiling todo-app v0.1.0 (/Users/jun/rust/todo-app)
    Finished dev [unoptimized + debuginfo] target(s) in 6.33s
     Running `target/x86_64-apple-darwin/debug/todo-app`
Hello, world!
cargo.tomlの[dependencies]にyewを追加する。
cargo.toml

[package]
name = "todo-app"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
yew = { git = "https://github.com/yewstack/yew/" }

続いてmain.rsを以下のように修正
main.rs

use yew::prelude::*;

#[function_component(App)]
fn app() -> Html {
    html! {
       < h1> { "Hello World" } </h1>
    }
}

fn main() {
    yew::start_app::<App>();
}

index.htmlをルートに作成して以下のように記述
index.html

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>todo app!</title>
</head>

<body>

</body>

</html>

devサーバーを立ち上げてブラウザを確認してみる。
% trunk serve --open
なんかエラー出た
error[E0425]: cannot find value `todo` in crate `yew`
  --> src/main.rs:11:10
   |
11 |     yew::start_app::<App>();
   |          ^^^^ not found in `yew`

error[E0425]: cannot find function `app` in this scope
  --> src/main.rs:11:15
   |
11 |     yew::start_app::<App>();
   |               ^^^ not found in this scope

For more information about this error, try `rustc --explain E0425`.
error: could not compile `todo-app` due to 2 previous errors
2022-07-08T16:09:55.694773Z ERROR ❌ error
yewが見つからないと言われている。 cargo.tomlの[dependencies]の書き方がいけない?
以下を参考にしてバージョンを指定して書き直してみた。
cargo.toml

[package]
name = "todo-app"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
yew = "0.19"
もう一回devサーバーを立ち上げてブラウザを確認してみる。
% trunk serve --open
今度はエラー出ず成功
http://127.0.0.1:8080/でブラウザ確認

Discussion

コメントにはログインが必要です。