【Rust】YewとAxumの連携
Yew で作ったWeb アプリケーションをAxum で作ったWeb サーバーで公開する
一方
🤔🤔🤔
二者の区別
そもそも
対して
今ホームページを読んでいて初めて知りましたが、yew_routerというものを使えば紛らわしいですね。
反対に
Yew を使う意義
本記事では特に述べませんが、
trunk serve
というコマンド一つで代替できると言えば、まるで融通利くもののように聞こえましょうか。この利点を応用できれば、
本題
私事ですが、以前投稿した記事にて
また、試行の上で次の記事を拝見し、参考にさせて頂きました。
準備
distというフォルダーが自動生成されます。この中に、あらかじめ用意するindex.htmlファイルと、生成された.jsファイル、.wasmファイルが存在するはずです。このdistフォルダーをそのまま移植するなどして流用します。
実装
-
作成package with_yewの名前で作成します。package作成cargo new with_yewwith_yewフォルダーが生成されるので、今回はdistフォルダーをこの中に移植します。 -
追加crate Cargo.toml[dependencies] axum = { version = "0.8.1", features = ["http2"] } tokio = { version = "1.42.0", features = ["full"] } tower-http = { version = "0.6.2", features = ["fs", "trace"] }コマンドで追加する場合は次のようにします。
crate追加cargo add axum --features http2 cargo add tokio --features full cargo add tower-http --features fs --features trace -
ソースコード記述
with_yew/src/main.rsに次の通り記述します。main.rsuse tower_http::{services::ServeDir, trace::TraceLayer}; use axum::Router; use tokio::net::TcpListener; #[tokio::main] async fn main() { const STATIC_DIR: &str = "./dist"; let serve_dir: ServeDir = ServeDir::new(STATIC_DIR); let app: Router = Router::new().nest_service("/dist", serve_dir); let listener: TcpListener = TcpListener::bind("127.0.0.1:8080").await.unwrap(); axum::serve(listener, app.layer(TraceLayer::new_for_http())).await.unwrap(); }要点
次に、
.htmlファイルを修正します。私の場合は、distフォルダー内に次のようなファイルが存在します。PS C:\⋯\with_yew> ls .\dist\ Directory: C:\⋯\with_yew\dist Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 2023/12/11(月) 2:26 1478457 bmi_calculator-c3e78f12e3a455f2_bg.wasm -a--- 2023/12/11(月) 2:26 25420 bmi_calculator-c3e78f12e3a455f2.js -a--- 2025/01/03(金) 6:21 1445 index.html修正するのは、(更新日が新しい通り)
index.htmlです。参考記事のおっしゃるように、.jsファイルと.wasmファイルの指定を変えなければなりませんでした。./フォルダー名/ファイル名の型式にすることで、正しく動作します。index.html(抜粋)<link rel="preload" href="./dist/bmi_calculator-c3e78f12e3a455f2_bg.wasm" as="fetch" type="application/wasm" crossorigin=""> <link rel="modulepreload" href="./dist/bmi_calculator-c3e78f12e3a455f2.js"> <script type="module">import init from './dist/bmi_calculator-c3e78f12e3a455f2.js';init('./dist/bmi_calculator-c3e78f12e3a455f2_bg.wasm');</script> -
実行
移植元は
ですが、今作成したものはYew ではないので、Yew trunk serveは使いません。実行cargo runブラウザーで
http://127.0.0.1:8080/distに接続すると、 で作成したアプリケーションがその通り表示されるはずです。Yew 証明書などは使用していないので
はprotocol http、IP とaddress 番号は、port TcpListener::bind("127.0.0.1:8080")としたので127.0.0.1:8080、 部はdirectory nest_service("/dist", serve_dir)としたので/distとなります。
Discussion