tauri簡(jiǎn)介
tauri 是一個(gè)新興的跨平臺(tái)GUI框架。與electron的基本思想相似,tauri的前端實(shí)現(xiàn)也是基于html系列語言。tauri的后端使用rust。官方形容,tauri可以創(chuàng)建體積更小、運(yùn)行更快、更加安全的跨平臺(tái)桌面應(yīng)用。
詳細(xì)的介紹可以自行去官網(wǎng)查看:
官網(wǎng)
Github
hello world
本人使用windows10系統(tǒng)。本hello world,實(shí)現(xiàn)了以tauri搭建桌面程序,在html頁面點(diǎn)擊按鍵后,由后臺(tái)rust反饋信息。
效果如下:

需準(zhǔn)備的文件
tauri 需要用到rust、nodejs,編譯器可使用vscode
官方文檔有比較詳細(xì)的環(huán)境搭建步驟,可參閱:
https://tauri.studio/docs/getting-started/intro
其中,當(dāng)搭建完環(huán)境,使用命令
yarn add tauri
安裝tauri包時(shí),可能會(huì)出現(xiàn)報(bào)錯(cuò):
pngquant failed to build, make sure that libpng-dev is installed
此錯(cuò)誤并不影響使用,可忽略。
程序結(jié)構(gòu)

初始化完成的tauri程序結(jié)構(gòu)如上圖所示。默認(rèn)情況下dist菜單用于存放實(shí)際的頁面文件。具體可在tauri.conf.json文件中進(jìn)行設(shè)置。
具體實(shí)現(xiàn)步驟如下:
在dist目錄創(chuàng)建index.html頁面,必須命名為index.html。頁面實(shí)現(xiàn)功能為一個(gè)簡(jiǎn)單的按鈕,點(diǎn)擊后向rust后臺(tái)發(fā)送信息,接收返回并顯示。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello from rust</title>
</head>
<body>
<input type="button" value="說hello" onclick="hello()"/>
<div id="result" style="width: 200px;height: 10px;"></div>
</body>
<script>
const TAURI=window.__TAURI__;
function hello() {
TAURI.promisified({
cmd:"hello",
name:encodeURI("小強(qiáng)")
}).then((res)=>{
document.querySelector("#result").innerHTML=decodeURI(res);
})
}
</script>
</html>
在
cmd.rs文件中,維護(hù)與前臺(tái)cmd:"hello"對(duì)應(yīng)的hello枚舉(enum)項(xiàng)。hello自身需要一個(gè)name作為參數(shù),另外,使用tauri框架的execute_promise()時(shí),還需要callback和error兩個(gè)參數(shù)。
cmd.rs的具體內(nèi)容如下:
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(tag = "cmd", rename_all = "camelCase")]
pub enum Cmd {
hello{name:String,callback:String,error:String}
}
在
main.rs中,進(jìn)行綁定hello枚舉項(xiàng):
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
mod cmd;
// use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
fn main() {
tauri::AppBuilder::new()
.invoke_handler(|_webview, arg| {
use cmd::Cmd::*;
match serde_json::from_str(arg) {
Err(e) => {
Err(e.to_string())
}
Ok(command) => {
match command {
//綁定前臺(tái)cmd鍵對(duì)應(yīng)的枚舉項(xiàng)
hello{name,callback,error}=>{
tauri::execute_promise(
_webview,
move || {
Ok(format!("hi {}.",name).to_string())
},
callback,
error,
)
}
}
Ok(())
}
}
})
.build()
.run();
}
運(yùn)行
yarn tauri build --release命令,或npm對(duì)應(yīng)的命令,生成程序??稍?br>src-tauri>target>release目錄下,找到生成的程序。