1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

既存プロジェクトへのTauriの追加

Last updated at Posted at 2024-08-17

公式が既存プロジェクトへの追加方法を提示してくれているので追加は簡単 (Tauri 公式)

インストールとAPIの呼び出しを行った

  • Cargo のインストール
  • プロジェクトへの Tauri の追加
  • Tauri API の呼び出し
  • Rust プロセスの呼び出し

※ Tauri 2.0 では import 対象など変更必要 (2024/10/7 追記)

Cargo のインストール

インストールが必要

Windowsではインストーラーからのインストールしかない模様

Visual Studio のインストールも併せて行われる

Cargo 公式

プロジェクトへの Tauri の追加

プロジェクトディレクトリでインストールコマンド実行
実行時にいくつか質問される。後で tauri.conf.json から修正可能

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

以下の項目は 既存プロジェクトに合わせるように設定が必要

  • 4.What is the URL of your dev server?
  • 5.What is your frontend dev command?
  • 6.What is your frontend build command?

React プロジェクトでデフォルトの状態から変えていなければ、

(4)dev serverは[http://localhost:3000](http://localhost:3000/), (5)dev commandはnpm run start, (6)build commandはnpm run build を設定

これらの設定は npm run tauri dev, npm run tauri build を行った時に、Tauri の処理に先立ってコマンドが実行される模様

最後にエラー対策で tauri.conf.json の identifier をデフォルトから変更する
名称は初期のものでなければなんでも可

Tauri API の呼び出し

例として fs (file system) を使用

src-tauri/tauri.conf.json の allowlist に fs を追加
scopeに関しては設定しなくても良いが設定しておく

"tauri": {
  "allowlist": {
    "fs": {
      "scope": ["$APPCONFIG/*"],
      "readFile": true,
      "writeFile": true,
      "readDir": true,
      "createDir": true,
      "exists": true
    }
  }
}

JavaScript 側

import { exists, BaseDirectory, readTextFile, writeTextFile } from '@tauri-apps/api/fs';

export const readSetting = async () => {
    const directory = BaseDirectory.AppConfig
    const fileName = 'conf.json'
    const existSetting = await exists(fileName, { dir: directory });

    if(!existSetting){
        await writeTextFile(fileName, JSON.stringify(DefaultSetting), { dir: directory });
    }
    const config = await readTextFile(fileName, { dir: directory });
    return {
        config: JSON.parse(config)
    }
}

const DefaultSetting = {
    color: '#8833AA'
}

Rust プロセスの呼び出し

src-tauri/src/main.rs でコマンドを定義し invoke_handler で追加

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

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

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

JavaScript 側

import { invoke } from '@tauri-apps/api'

export const readSetting = async () => {
	return await invoke('greet', { name: 'World' })
}
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?