Tauri 入门教程

在这里插入图片描述

1 简介

Tauri:构建跨平台的快速、安全、前端隔离应用。Tauri 是一个相对较新的框架,允许您利用基本的 Web 技术和 Rust 编程语言快速创建跨平台应用程序。Tauri 基于 Rust 构建,在设计上具有安全性和高性能,与任何前端框架兼容,并允许您为所有主要桌面平台(包括 macOSWindowsLinux 操作系统)创建可执行应用程序。

每个 Tauri 应用程序都包含一个核心进程,作为应用程序的入口点,并且是唯一可以完全访问操作系统的组件。然而,核心进程并不呈现实际的应用程序界面;相反,它会启动使用操作系统提供的 WebView 库的子进程,从而可以使用 Web 技术构建 Tauri 应用程序。

Electron 不同,它使用 Chromium 引擎打包和呈现您的应用程序,而不管底层操作系统如何,Tauri 使用操作系统的 WebView 库。Tauri 方法的优点是 WebView 库不包含在最终的可执行文件中,而是在运行时动态链接,这大大降低了捆绑应用程序的大小和性能。

如前所述,Tauri 应用程序由于其 webview 方法而比 Electron 应用程序轻得多。事实上,使用 Electron 构建的重量超过 52MB 的示例应用程序在使用 Tauri 构建时会轻得多,大约 3MB。

Tauri 框架的其他一些主要优势包括:

  • 更好的性能:Tauri 应用程序在性能、启动时间和内存消耗方面也优于 Electron 应用程序
  • 自更新器:Tauri 包含一个自更新器功能,您可以在不依赖任何第三方库的情况下快速将其集成到您的应用程序中
  • 跨平台:当然,您可以为所有主要桌面操作系统生成可执行文件

2 创建Tauri项目(页面基于Vue)

2.1 环境准备

大家需要根据自己的开发环境预先准备下,操作参考官网文档:预先准备

2.2 创建工程

控制台执行:

npm create tauri-app

然后输入项目名称,会自动生成目录,选择包管理工具,选择UI模板,这里我选择Vue,还可以选择react 等前端模板框架:
在这里插入图片描述
创建完成后,进入到对应目录,安装依赖,再运行tarui

npm install
npm run tauri dev

经过编译后就自动弹出程序的窗口,里面的页面就是Vue构建的页面:
在这里插入图片描述

3 Tauri 工程目录介绍

在这里插入图片描述
整个目录结构其实跟vue项目目录很像,只是多了一个src-tauri目录,这个目录是 Tauri 项目配置目录,里面包含了程序的图标 、rust源码、构建后的文件、tauri配置文件。我们在写软件的过程中,有遇到前端不能解决的问题,一般是通过调用rust程序来解决。所以在做一些高级功能的时候我们需要会一点rust知识。

4 页面调用rust方法

src-tauri/src/main.rs 中加入前端要调用的方法:

#[tauri::command]
fn my_custom_command() {
  println!("I was invoked from JS!");
}

// Also in main.rs
fn main() {
  tauri::Builder::default()
    // This is where you pass in your commands
    .invoke_handler(tauri::generate_handler![my_custom_command])
    .run(tauri::generate_context!())
    .expect("failed to run app");
}

前端调用,可以写在前端的某个事件调用方法里:

// When using the Tauri API npm package:
import { invoke } from '@tauri-apps/api/tauri'

// Invoke the command
invoke('my_custom_command')

传参数和返回参数:

#[tauri::command]
fn my_custom_command(invoke_message: String) -> String {
  println!("I was invoked from JS, with this message: {}", invoke_message);
  invoke_message
}

注意:rust定义参数的时候使用下划线,js调用的时候使用驼峰命名。

invoke('my_custom_command', { invokeMessage: 'Hello!' }).then((message) => console.log(message))

invoke返回的是Promise ,可以使用 async/await 用同步的方式写。

5 事件系统

前端触发并监听方法:

import { invoke } from "@tauri-apps/api/tauri";
import { listen } from '@tauri-apps/api/event'

const unlisten = async () => {
  await invoke('init_process'); // 调用rust任务
  await listen('my-event', event => { // 监听事件
    console.log(event)
  })
}
</script>
<template>
  <button @click="unlisten">开启事件监听</button>
</template>

rust 发送事件方法:

use tauri::Window;
use std::{thread, time};

#[derive(Clone, serde::Serialize)]
struct Payload {
  message: String,
}

#[tauri::command]
fn init_process(window: Window) {
  std::thread::spawn(move || {
    loop { // 循环触发
      window.emit("my-event", Payload { message: "Tauri is awesome!".into() }).unwrap(); // 前端自动解析为对象
      thread::sleep(time::Duration::from_millis(1000)); // 每隔一秒执行
    }
  });
}

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

6 HTTP请求

使用 tauri 访问HTTP请求需要在tauri.conf.json设置白名单:

{
  "tauri": {
    "allowlist": {
      "http": {
        "all": true, // enable all http APIs
        "request": true // enable HTTP request API
      }
    }
  }
}

但是这样写不安全,建议仅将您使用的 API 列入白名单,以获得最佳的安装包大小和安全性。

{
  "tauri": {
    "allowlist": {
      "http": {
        "scope": ["https://api.github.com/repos/tauri-apps/*"]
      }
    }
  }
}

前端使用:

import { fetch } from '@tauri-apps/api/http';
const response = await fetch('http://localhost:3003/users/2', {
  method: 'GET',
  timeout: 30,
  responseType: 2  // 1-JSON 2-Text 3-Binary
});

7 文件系统

{
  "tauri": {
    "allowlist": {
      "fs": {
        "scope": ["$APPDATA/databases/*"]
      }
    }
  }
}

此作用域配置仅允许访问 $APPDATA 目录的数据库文件夹中的文件,注意 $APPDATA 变量的使用。该值在运行时注入,解析为应用程序数据目录。可用的变量是:

  • $APPCONFIG => C:\Users\15114\AppData\Roaming\com.tauri.dev\
  • $APPDATA => C:\Users\15114\AppData\Roaming\com.tauri.dev\
  • $APPLOCALDATA => C:\Users\15114\AppData\Local\com.tauri.dev\
  • $APPCACHE => C:\Users\15114\AppData\Local\com.tauri.dev\
  • $APPLOG => C:\Users\15114\AppData\Roaming\com.tauri.dev\logs\
  • $AUDIO => C:\Users\15114\Music\
  • $CACHE => C:\Users\15114\AppData\Local\
  • $CONFIG => C:\Users\15114\AppData\Roaming\
  • $DATA => C:\Users\15114\AppData\Roaming\
  • $LOCALDATA => C:\Users\15114\AppData\Local\
  • $DESKTOP => C:\Users\15114\Desktop\
  • $DOCUMENT => C:\Users\15114\Documents\
  • $DOWNLOAD => C:\Users\15114\Downloads\
  • $EXE,
  • $FONT,
  • $HOME => C:\Users\15114\
  • $PICTURE => C:\Users\15114\Pictures\
  • $PUBLIC => C:\Users\Public\
  • $RUNTIME,
  • $TEMPLATE => C:\Users\15114\AppData\Roaming\Microsoft\Windows\Templates\
  • $VIDEO => C:\Users\15114\Videos\
  • $RESOURCE => \?\F:\project\demo\rust\tauri-demo\src-tauri\target\debug\
  • $APP, 即将弃用
  • $LOG, 即将弃用
  • $TEMP
import { copyFile,createDir, BaseDirectory } from '@tauri-apps/api/fs';

// Copy the `$APPCONFIG/app.conf` file to `$APPCONFIG/app.conf.bk`
await copyFile('app.conf', 'app.conf.bk', { dir: BaseDirectory.AppConfig });
// Create the `$APPDATA/users` directory
await createDir('users', { dir: BaseDirectory.AppData, recursive: true });

8 对话框

添加 tauri.allowlist.dialogtauri.conf.json

{
  "tauri": {
    "allowlist": {
      "dialog": {
        "all": true, // enable all dialog APIs
        "open": true, // enable file open API
        "save": true // enable file save API
      }
    }
  }
}
import { ask } from '@tauri-apps/api/dialog';
const yes = await ask('Are you sure?', 'Tauri');
const yes2 = await ask('This action cannot be reverted. Are you sure?', { title: 'Tauri', type: 'warning' });

9 窗口配置

tauri.config.json 中关于窗口的主要配置:

{
  "tauri": {
    "windows": [
      {
      	"center": true, // 窗口显示在屏幕中间
      	"x": 100, // 窗口显示x坐标
      	"y": 100, // 窗口显示y坐标
        "fullscreen": false, // 是否全屏
        "height": 600, // 窗口高度
        "width": 800, // 窗口宽度
        "resizable": true, // 是否可以resize
        "title": "Tauri App", // 窗口标题
        "decorations": true // 是否显示边框和状态栏
      }
    ]
  }
}

10 打包

修改 tauri.config.jsontauri.bundle.identifier ,这是一个唯一标识,可以为软件的名称。
控制台执行命令:

npm run tauri build

这个命令会先编译前端项目,相当于先执行 npm run build 编译出前端静态文件到 dist 目录:
在这里插入图片描述
然后回编译 rust 组件,最后生成一个 msi 安装文件:
在这里插入图片描述
这个文件在windows系统可以直接双击安装,最后显示界面和开发界面是一样的。

在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优小U

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值