LoginSignup
0
1

【Rust】Yewを使ってフロント実装します。その0: 開発準備編

Last updated at Posted at 2023-12-06

こんにちは!

突然ですが、皆さんRustというプログラミング言語をご存じですか?
Rustはゼロコスト抽象化や所有権システムなどのユニークな機能を持ち、質の高いパフォーマンスやメモリ安全性を確保します。

Javascript runtime である Deno やレガシーシステムである Adobe Flash Player をエミュレートする Ruffle 、 Discord の代替オープンソースプラットフォームである Revolt 、Pythonにおけるリントやフォーマットを統合して置き換えることができる Ruff 、 Linux カーネルを使用せず Rust で実装された Redox OS など、幅広い分野で使用されています。

Rust のクレートの中には Yew という WebAssembly を経由してフロントエンドの実装ができるものがあります。
このアーティクルでは Rust で Yew を使ってプログラミングするため準備を詳しく書きます。
よろしくお願いします!

Rust のインストール

初めに Rust をインストールしましょう!

Windows11 の場合は、 winget install -i Microsoft.VisualStudio.2022.BuildTools コマンドを実行して、起動した Visual Studio Installer から Desktop development with C++ をインストールしておきましょう。
そのあとに rustup-init.exe を実行して画面に従いながら操作すればインストール完了です。

Linux の場合は build-essential をインストールしてから curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh コマンドを実行してインストールします。

Mac の場合は xcode-select --install または Homebrew をインストールしてから curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh コマンドを実行してインストールします。

コマンドラインで rustup --versioncargo --version を実行してバージョンが表示されれば正常にインストールされています。

コーディングエディタのインストール

このアーティクルではコーディングエディタとして Visual Studio Code を紹介します!
Web ページで配布しているインストールバイナリを実行してインストールします。

インストールできたら、 Rust でコーディングするために拡張機能をインストールします。

Rust プロジェクトではクレートを管理するために toml ファイルを使用するため Toml をサポートするための拡張機能もインストールしましょう。

さらに今回は Yew を使うので追加で rust-yew 拡張機能もインストールします。


Rust でコーディングするための環境ができたら Rust の勉強をしましょう。
Rust の基本的な文法やビルトイン機能について、体系的にまとめられたアーティクルがあります。

Rust コミュニティは活発に活動しており、様々な言語への翻訳版も存在するので探してみましょう。

Trunk のインストール

Rust で Wasm アプリケーションをビルド・デプロイするときは Trunk を使用すると簡単です。
Trunk 自体も Rust で開発されており cargo install trunk コマンドからインストールできます。

Yew の動作確認

それでは動作確認のために Yew の Getting Started に沿ってサンプルアプリケーションを実行してみましょう!

はじめに cargo コマンドでプロジェクトを作成し、そのディレクトリを visual Studio Code で開きます。

$ cargo new yew-app --vcs none
$ cd yew-app
$ code ./

プロジェクトを開けたら、 Yew クレートを追加します。

$ cargo add yew --features csr
    Updating crates.io index
      Adding yew v0.21.0 to dependencies.
             Features:
             + csr
             - hydration
             - ssr
    Updating crates.io index

Cargo.toml ファイルを開いて Yew が追加できたか確認しましょう。

Cargo.toml
[package]
name = "yew-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 = { version = "0.21.0", features = ["csr"] }

[dependencies] に yew が追加されていればOKです!

次に Yew のサンプルアプリページを参考に main.rs ファイルをコピー&ペーストします。

src/main.rs
use yew::prelude::*;

#[function_component]
fn App() -> Html {
    let counter = use_state(|| 0);
    let onclick = {
        let counter = counter.clone();
        move |_| {
            let value = *counter + 1;
            counter.set(value);
        }
    };

    html! {
        <div>
            <button {onclick}>{ "+1" }</button>
            <p>{ *counter }</p>
        </div>
    }
}

fn main() {
    yew::Renderer::<App>::new().render();
}

さらに Trunk を使うための index.html ファイルを追加します。

index.html
<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Yew App</title>
    </head>
    <body></body>
</html>

これで準備は整いました!
trunk serve コマンドを使って Yew アプリをビルドしましょう!

$ trunk serve
2023-12-06T04:52:40.638626Z  INFO 📦 starting build
2023-12-06T04:52:40.641168Z  INFO spawning asset pipelines
2023-12-06T04:52:40.938112Z  INFO building yew-app
error[E0463]: can't find crate for `core`                                                          
  |
  = note: the `wasm32-unknown-unknown` target may not be installed
  = help: consider downloading the target with `rustup target add wasm32-unknown-unknown`

error[E0463]: can't find crate for `compiler_builtins`

For more information about this error, try `rustc --explain E0463`.
error: could not compile `cfg-if` (lib) due to 2 previous errors
warning: build failed, waiting for other jobs to finish...
2023-12-06T04:52:42.472675Z ERROR ❌ error
error from HTML pipeline

Caused by:
    0: error from asset pipeline
    1: error during cargo build execution
    2: cargo call returned a bad status
Error: error from HTML pipeline

もしも上記のようにエラーが出た場合は Wasm をビルドするためのターゲットアーキテクチャが追加されていないので、エラーメッセージに従って追加しましょう。

$ rustup target add wasm32-unknown-unknown
info: downloading component 'rust-std' for 'wasm32-unknown-unknown'
info: installing component 'rust-std' for 'wasm32-unknown-unknown'
 17.1 MiB /  17.1 MiB (100 %)  19.7 MiB/s in  1s ETA:  0s

それでは改めて trunk serve を実行します。

$ trunk serve
2023-12-06T05:03:11.135766Z  INFO 📦 starting build
2023-12-06T05:03:11.138080Z  INFO spawning asset pipelines
2023-12-06T05:03:11.461127Z  INFO building yew-app
    Finished dev [unoptimized + debuginfo] target(s) in 0.13s
2023-12-06T05:04:01.644929Z  INFO fetching cargo artifacts
2023-12-06T05:04:02.019582Z  INFO processing WASM for yew-app
2023-12-06T05:04:02.181645Z  INFO using system installed binary app=wasm-bindgen version=0.2.88
2023-12-06T05:04:02.183036Z  INFO calling wasm-bindgen for yew-app
2023-12-06T05:04:02.407729Z  INFO copying generated wasm-bindgen artifacts
2023-12-06T05:04:02.415781Z  INFO applying new distribution
2023-12-06T05:04:02.435625Z  INFO ✅ success
2023-12-06T05:04:02.437224Z  INFO 📡 serving static assets at -> /
2023-12-06T05:04:02.440592Z  INFO 📡 server listening at http://127.0.0.1:8080

エラーが出ることなくビルドできていれば Web ブラウザから yew-app を閲覧することができます!
Web ブラウザを開いて 127.0.0.1:8080 にアクセスしてみましょう。

yew-app-sample.png

「+1」と書かれたボタンと 0 が表示されましたか?
「+1」と書かれたボタンを押すと、下に表示される数字が 1 ずつ増えていくはずです。
正常に動作していれば、 Yew で開発をするための準備と動作確認は完了です!
お疲れさまでした!


次のアーティクルでは Yew の現状の機能の一部を紹介したいと思います。

不定期の更新になりますが、何か簡単な機能を持った(だけど便利で誰かの役に立つ)アプリケーションを開発するところまで連載したいと思っています。
アイディア募集中です!よろしくお願いいたします!
ありがとうございました!


この文章の一部は Chat-GPT 3.5 によって和文校正されています。

お知らせ

DONUTSでは新卒中途問わず積極的に採用活動を行っています。
詳細はこちらをご確認ください。

ジョブカン事業部のエンジニア募集はこちら。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1