raspberrypi
Ubuntu Server をインストールした Raspberry Pi 4 に Rust 開発環境と WebAssembly 開発環境を整備する。
「実践Rustプログラミング入門」の「Chapter 6 WebAssembly」の内容を実行する。
https://www.shuwasystem.co.jp/book/9784798061702.html
Raspberry Pi 向け Ubuntu のページ
https://ubuntu.com/download/raspberry-pi
Ubuntu Server 20.04.1 LTS
Raspberry Pi 4 64-bit をインストール
インストールガイド
https://ubuntu.com/tutorials/how-to-install-ubuntu-on-your-raspberry-pi#1-overview
ヘッドレスでインストールするには system-boot/network-config
を編集してねと書いてあるが、うまくいかなかった。
Raspberry Pi OS と同様に wpa_supplicant.conf
を使って設定できた。
ssh で Raspberry Pi 4 にログインし、以下のコマンドを実行する。
途中で聞かれるインストール番号は default の 1 (1) Proceed with installation (default))
を入力する。
インストールが終了したら、source
でパスを通す。
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
$ source $HOME/.cargo/env
バージョンを確認する。
$ cargo --version
cargo 1.48.0 (65cbdd2dc 2020-10-14)
$ rustc --version
rustc 1.48.0 (7eac88abb 2020-11-16)
VSCode の Remote - SSH
Extension を使って、Raspberry Pi 4 にログインしてセットアップした。
Rust 関連の Extension は rust-analyzer
、CodeLLDB
、Better TOML
をインストールした。
nvm、npm をインストールする。
$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
$ source ~/.bashrc
$ nvm install --lts
$ npm --version
6.14.8
cargo-generate のインストールに必要なパッケージをインストールした後、cargo-generate をインストールする。
$ sudo apt install gcc clang make openssl pkg-config libssl-dev
$ cargo install cargo-generate
cargo-generate でプロジェクトを作成する。
プロジェクト名を wasm_example
と入力する。
$ cargo generate --git https://github.com/rustwasm/wasm-pack-template
Project Name: wasm_example
wasm のプロジェクトが作成される。
wasm-pack をインストールする。
$ cargo install wasm-pack
Raspberry Pi 4 では install shell がエラーになってしまったので、
cargo install
でインストールしました。
https://rustwasm.github.io/wasm-pack/installer/#
wasm バイナリをビルドする。
$ cd wasm_example
$ wasm-pack build
以下のようなエラーが出た。
Error: no prebuilt wasm-opt binaries are available for this platform: Unrecognized target!
To disable `wasm-opt`, add `wasm-opt = false` to your package metadata in your `Cargo.toml`.
Cargo.toml
に、以下のオプションを記載する。
wasm_example/Cargo.toml
[package.metadata.wasm-pack.profile.release]
wasm-opt = false
再度ビルドする。
pkg/wasm_example_bg.wasm
が作成されていれば OK 。
$ wasm-pack build
...
[INFO]: :-) Your wasm pkg is ready to publish at /***/wasm_example/pkg.
npm コマンドで Web アプリケーションを作成する。
$ npm init wasm-app www
npx: installed 1 in 3.417s
🦀 Rust + 🕸 Wasm = ❤
$ cd www
$ npm install
localhost 以外からも参照できるように wasm_example/www/package.json
を編集する。
...
"scripts": {
"build": "webpack --config webpack.config.js",
"start": "webpack-dev-server"
↓↓↓
"start": "webpack-dev-server --host 0.0.0.0"
},
...
Web アプリケーションを実行する。
$ npm run start
...
ℹ 「wdm」: Compiled successfully.
ブラウザから、http://<Raspberry Pi 4 の IP アドレス>:8080
にアクセスする。
「Hello, hello-wasm-pack!」が表示されれば成功。