Closed7

Tauri + Astroでデスクトップアプリを作成する

jajimajajima

Astroプロジェクトを作成

npm create astro@latest
✔ Where would you like to create your new project? … .
✔ How would you like to setup your new project? › an empty project
✔ Would you like to install npm dependencies? (recommended)yes
✔ Would you like to initialize a new git repository? (optional) … no
✔ How would you like to setup TypeScript? › Strict
jajimajajima

Tauri CLIをインストール

npm install --save-dev @tauri-apps/cli

npm scriptsを追加

package.json
   "scripts": {
     ...
+    "tauri": "tauri"
   },
   "dependencies": {
     "astro": "^1.7.1"
jajimajajima

Tauriを導入

npm run tauri init
✔ What is your app name? · tauri-astro
✔ What should the window title be? · tauri-astro
✔ Where are your web assets (HTML/CSS/JS) located, relative to the "<current dir>/src-tauri/tauri.conf.json" file that will be created? · ../dist
✔ What is the url of your dev server? · http://localhost:3000
✔ What is your frontend dev command? · npm run dev
✔ What is your frontend build command? · npm run build

ここまでの設定で、Tauriの開発ビルドが可能になっている

npm run tauri dev

アプリのビルド → インストールも可能

npm run tauri build

そのまま行うと、src-tauri/tauri.conf.jsontauri.bundle.identifierを設定していないことによるエラーが生じるが、コンソール出力の通りに修正すればOK

jajimajajima

Greet機能の実装

Tauriアプリをボイラープレートから作成すると実装されているGreetの機能を実装する。

バックエンド

src-tauri/src/main.rsにgreet関数を追加

main.rs
#[tauri::command]
fn greet(name: &str) -> String {
   format!("Hello, {}!", name)
}

invoke_handlersgreetを追加

main.rs
 fn main() {
   tauri::Builder::default()
+    .invoke_handler(tauri::generate_handler![greet])
     .run(tauri::generate_context!())
     .expect("error while running tauri application");
 }
jajimajajima

フロントエンド

Tauri APIをインストール

npm install @tauri-apps/api

src/components/Greet.astroを実装

Greet.astro
---
---

<div>
  <input
    id="name"
    type="text"
    placeholder="Enter a name..."
  />
  <button id="greet">Greet</button>
  <div id="res" />
</div>

<script>
  import { invoke } from '@tauri-apps/api'
  document.getElementById('greet')?.addEventListener('click', async () => {
    const name = document.getElementById('name')?.value
    const res = await invoke('greet', { name })
    document.getElementById('res')!.innerText = `${res} You've been greeted from Rust!`
  })
</script>

src/pages/index.astroでGreetコンポーネントを呼び出し

index.astro
---
import Greet from '../components/Greet.astro'
---
// (略)
        </head>
        <body>
                <h1>Astro</h1>
+               <Greet />
        </body>
jajimajajima

ここまでの実装で、greet機能を持ったTauri + Astroアプリが作成できた

このスクラップは2022/12/21にクローズされました