Rust GUI框架Tauri V1 入门

news/2024/9/18 22:21:35 标签: rust

文章目录

  • Tauri介绍
  • Vite
  • 开始
    • 创建 Rust 项目
  • 调用指令
    • window.__TAURI_INVOKE__.invoke is undefined 问题
  • 参考资料
    • JavaScript 模块
      • Vue 框架
      • Vue Route
      • vite
      • Nuxt
    • gitignore文件
    • 上传到csdn gitcode
      • 网站端
      • 本地端
    • gitcode发布

Tauri介绍

Tauri是一款用Rust构建的开源框架,用于创建轻量级、安全且高效的桌面应用程序。它将Rust的强大功能与Web技术(如HTML、CSS和JavaScript)相结合,提供了一种现代的、跨平台的方式来开发桌面应用。Tauri的核心理念是“最小权限原则”,只在必要时调用操作系统API,以降低攻击面。

Vite

Vite 是一个前端构建包,它在开发过程中提供了各种“生活质量”功能,例如 热模块重载 (HMR)。 在构建生产环境时,它也会将你的源代码转换成最优化的 HTML、CSS 和 JavaScript。 我们推荐使用快速、易配置、拥有 丰富插件生态的Vite。

Vite comes with a scaffolding utility similar to create-tauri-app that can quickly set up a new project from many pre-defined templates. 您可以从许多前端框架中选择,如 React、Svelte 或 Vue。 在本指南中,我们将选择 vanilla-ts 模板来创建一个 没有 任何前端框架的简单项目。

开始

getting-started-vite

创建项目pnpm create vite

√ Project name: ... helloworld001
√ Select a framework: » Vanilla
√ Select a variant: » JavaScript

Scaffolding project in D:\taui\helloworld001...

接下来

cd helloworld001

简单说明一下

  1. 项目名称
    这将是您的 JavaScript 项目的名称,这里是helloworld001。 对应此工具将创建的文件夹的名称,但在其他方面对你的应用没有影响。 您可以在此处填写任何您想要的名称。
  2. 选择一个框架
    如果您计划之后使用一个前端框架,这里选择Vanilla.js
  3. 选择一个语言
    这里选择 原生JavaScript

当通过 vite 命令启动前端时,Vite 将在项目根目录中寻找名为 vite.config.ts 的配置文件。 我们想要自定义此文件以获得与 Tauri的最佳兼容性。

如果它不是由上面的脚手架创建的(例如如果你正在使用原版的 JavaScript),你可能需要创建 vite.config.ts 文件。

手动创建helloworld001\vite.config.ts文件

import { defineConfig } from 'vite'

export default defineConfig({
  // prevent vite from obscuring rust errors
  clearScreen: false,
  // Tauri expects a fixed port, fail if that port is not available
  server: {
    strictPort: true,
  },
  // to access the Tauri environment variables set by the CLI with information about the current target
  envPrefix: ['VITE_', 'TAURI_PLATFORM', 'TAURI_ARCH', 'TAURI_FAMILY', 'TAURI_PLATFORM_VERSION', 'TAURI_PLATFORM_TYPE', 'TAURI_DEBUG'],
  build: {
    // Tauri uses Chromium on Windows and WebKit on macOS and Linux
    target: process.env.TAURI_PLATFORM == 'windows' ? 'chrome105' : 'safari13',
    // don't minify for debug builds
    minify: !process.env.TAURI_DEBUG ? 'esbuild' : false,
    // 为调试构建生成源代码映射 (sourcemap)
    sourcemap: !!process.env.TAURI_DEBUG,
  },
})

创建 Rust 项目

每款 Tauri 应用的核心都是由一个管理窗口的 Rust 二进制文件、WebView 和进行系统调用的 tauri Rust 包构成。 此项目使用官方的软件包管理器及 Rust 通用构建工具 Cargo 来管理。

我们的 Tauri CLI 工具会在底层自动调用 Cargo,所以您大部分情况下无需和其交互。 Cargo 有诸多我们的 CLI 工具所未提供的有用功能,包括测试、分析及格式化工具。请参阅其官方文档来了解更多。

安装 TAURI CLI

pnpm add --save-dev @tauri-apps/cli

将 Tauri 的 CLI 工具作为开发依赖添加到你的项目中,使得你可以在项目中方便地使用 Tauri 提供的命令来构建和管理你的桌面应用程序。
要搭建一个使用 Tauri 的简单 Rust 项目,请打开终端并运行如下命令:

$ pnpm tauri init
✔ What is your app name? · helloworld001
✔ What should the window title be? · helloworld001
✔ 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:5173
✔ What is your frontend dev command? · pnpm run dev
✔ What is your frontend build command? · pnpm run build

填入如下

helloworld001
helloworld001
../dist
http://localhost:5173
pnpm run dev
pnpm run build

接下来

pnpm install
pnpm tauri dev

原来在浏览器显示的,可以通过窗口显示出来。
在这里插入图片描述

pnpm tauri dev输出如下

     Running BeforeDevCommand (`pnpm run dev`)

> helloworld001@0.0.0 dev D:\taui\helloworld001
> vite


  VITE v5.4.4  ready in 412 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
        Info Watching D:\taui\helloworld001\src-tauri for changes...
   Compiling cfg-if v1.0.0
   Compiling byteorder v1.5.0
   Compiling siphasher v0.3.11
   Compiling memchr v2.7.4
   Compiling windows_x86_64_msvc v0.52.6
   Compiling itoa v1.0.11
   Compiling serde v1.0.210
   Compiling ryu v1.0.18
   Compiling getrandom v0.2.15
   Compiling windows-targets v0.52.6
   Compiling getrandom v0.1.16
   Compiling smallvec v1.13.2
   Compiling rand_core v0.6.4
   Compiling phf_shared v0.10.0
   Compiling zerocopy v0.7.35
   Compiling rand_core v0.5.1
   Compiling hashbrown v0.14.5
   Compiling equivalent v1.0.1
   Compiling rand_pcg v0.2.1
   Compiling phf_shared v0.8.0
   Compiling fnv v1.0.7
   Compiling scopeguard v1.2.0
   Compiling once_cell v1.19.0
   Compiling log v0.4.22
   Compiling lock_api v0.4.12
   Compiling thiserror v1.0.63
   Compiling parking_lot_core v0.9.10
   Compiling windows-sys v0.59.0
   Compiling new_debug_unreachable v1.0.6
   Compiling bitflags v1.3.2
   Compiling ppv-lite86 v0.2.20
   Compiling tinyvec_macros v0.1.1
   Compiling indexmap v2.5.0
   Compiling parking_lot v0.12.3
   Compiling precomputed-hash v0.1.1
   Compiling mac v0.1.1
   Compiling futf v0.1.5
   Compiling darling_core v0.20.10
   Compiling tinyvec v1.8.0
   Compiling rand_chacha v0.3.1
   Compiling rand_chacha v0.2.2
   Compiling rand v0.8.5
   Compiling rand v0.7.3
   Compiling dtoa v1.0.9
   Compiling utf-8 v0.7.6
   Compiling unicode-normalization v0.1.23
   Compiling dtoa-short v0.3.5
   Compiling tendril v0.4.3
   Compiling winapi-util v0.1.9
   Compiling phf v0.10.1
   Compiling phf_generator v0.8.0
   Compiling phf_generator v0.10.0
   Compiling phf_codegen v0.8.0
   Compiling phf_shared v0.11.2
   Compiling string_cache_codegen v0.5.2
   Compiling phf_codegen v0.10.0
   Compiling phf_macros v0.8.0
   Compiling selectors v0.22.0
   Compiling alloc-no-stdlib v2.0.4
   Compiling itoa v0.4.8
   Compiling stable_deref_trait v1.2.0
   Compiling percent-encoding v2.3.1
   Compiling nodrop v0.1.14
   Compiling serde_json v1.0.128
   Compiling string_cache v0.8.7
   Compiling unicode-bidi v0.3.15
   Compiling markup5ever v0.11.0
   Compiling matches v0.1.10
   Compiling servo_arc v0.1.1
   Compiling form_urlencoded v1.2.1
   Compiling idna v0.5.0
   Compiling alloc-stdlib v0.2.2
   Compiling phf_generator v0.11.2
   Compiling phf v0.8.0
   Compiling same-file v1.0.6
   Compiling cssparser v0.27.2
   Compiling fxhash v0.2.1
   Compiling uuid v1.10.0
   Compiling hashbrown v0.12.3
   Compiling thin-slice v0.1.1
   Compiling cfb v0.7.3
   Compiling url v2.5.2
   Compiling indexmap v1.9.3
   Compiling walkdir v2.5.0
   Compiling darling_macro v0.20.10
   Compiling phf_macros v0.11.2
   Compiling brotli-decompressor v4.0.1
   Compiling darling v0.20.10
   Compiling html5ever v0.26.0
   Compiling serde_with_macros v3.9.0
   Compiling libc v0.2.158
   Compiling dunce v1.0.5
   Compiling infer v0.13.0
   Compiling toml_datetime v0.6.8
   Compiling serde_spanned v0.6.7
   Compiling phf v0.11.2
   Compiling brotli v6.0.0
   Compiling aho-corasick v1.1.3
   Compiling windows-version v0.1.1
   Compiling glob v0.3.1
   Compiling windows_x86_64_msvc v0.39.0
   Compiling kuchikiki v0.8.2
   Compiling crossbeam-utils v0.8.20
   Compiling jsonptr v0.4.7
   Compiling vswhom-sys v0.1.2
   Compiling serde_with v3.9.0
   Compiling regex-automata v0.4.7
   Compiling json-patch v2.0.0
   Compiling windows v0.39.0
   Compiling adler2 v2.0.0
   Compiling toml_edit v0.22.20
   Compiling miniz_oxide v0.8.0
   Compiling toml_edit v0.19.15
   Compiling winapi v0.3.9
   Compiling crc32fast v1.4.2
   Compiling tauri-utils v1.6.1
   Compiling regex v1.10.6
   Compiling bytes v1.7.1
   Compiling toml v0.8.19
   Compiling toml v0.7.8
   Compiling flate2 v1.0.33
   Compiling dirs-sys-next v0.1.2
   Compiling vswhom v0.1.0
   Compiling winreg v0.52.0
   Compiling num-traits v0.2.19
   Compiling webview2-com-sys v0.19.0
   Compiling color_quant v1.1.0
   Compiling bytemuck v1.18.0
   Compiling raw-window-handle v0.5.2
   Compiling image v0.24.9
   Compiling embed-resource v2.4.3
   Compiling png v0.17.13
   Compiling dirs-next v2.0.0
   Compiling http v0.2.12
   Compiling semver v1.0.23
   Compiling anyhow v1.0.88
   Compiling crossbeam-channel v0.5.13
   Compiling instant v0.1.13
   Compiling regex-syntax v0.8.4
   Compiling lazy_static v1.5.0
   Compiling unicode-segmentation v1.11.0
   Compiling sha2 v0.10.8
   Compiling ico v0.3.0
   Compiling tauri-winres v0.1.1
   Compiling cargo_toml v0.15.3
   Compiling crossbeam-epoch v0.9.18
   Compiling bstr v1.10.0
   Compiling http-range v0.1.5
   Compiling pin-project-lite v0.2.14
   Compiling tauri-codegen v1.4.5
   Compiling globset v0.4.15
   Compiling tauri-build v1.5.4
   Compiling crossbeam-deque v0.8.5
   Compiling slab v0.4.9
   Compiling tauri v1.7.2
   Compiling filetime v0.2.25
   Compiling pin-utils v0.1.0
   Compiling futures-core v0.3.30
   Compiling fastrand v2.1.1
   Compiling futures-task v0.3.30
   Compiling futures-util v0.3.30
   Compiling tempfile v3.12.0
   Compiling serialize-to-javascript v0.1.2
   Compiling tar v0.4.41
   Compiling ignore v0.4.23
   Compiling tokio v1.40.0
   Compiling tauri-macros v1.4.6
   Compiling encoding_rs v0.8.34
   Compiling state v0.5.3
   Compiling app v0.1.0 (D:\taui\helloworld001\src-tauri)
   Compiling tao v0.16.10
   Compiling webview2-com v0.19.1
   Compiling tauri-runtime v0.14.5
   Compiling wry v0.24.11
   Compiling tauri-runtime-wry v0.14.10
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 2m 10s

调用指令

Tauri 为您的前端开发提供了其他系统原生功能。 我们将其称作指令,这使得您可以从 JavaScript 前端调用由 Rust 编写的函数。 由此,您可以使用性能飞快的 Rust 代码处理繁重的任务或系统调用。

以下是一个简单示例:

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

一个指令等于一个普通的 Rust 函数,只是还加上了 #[tauri::command] 宏来让其与您的 JavaScript 环境交互。

指令 =  普通的Rust 函数

修改helloworld001\src-tauri\src\main.rs文件为以下内容

rust">// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

fn main() {
    //tauri::Builder::default()
    //    .run(tauri::generate_context!())
    //    .expect("error while running tauri application");

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

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

最后,我们需要让 Tauri 知悉您刚创建的指令才能让其调用。
我们需要使用 .invoke_handler() 函数及 Generate_handler![] 宏来注册指令:

使用 @tauri-apps/api JavaScript 库来调用新创建的命令, 通过 JavaScript 访问诸如窗口、文件系统等核心功能, 您可以使用自己喜欢的 JavaScript 包管理器来安装。

pnpm add @tauri-apps/api

JavaScript 库安装之后,您就可以在 main.js 中调用指令了:

main.js文件

// access the pre-bundled global API functions
const { invoke } = window.__TAURI__.tauri

// now we can call our Command!
// You will see "Welcome from Tauri" replaced
// by "Hello, World!"!
invoke('greet', { name: 'World' })
  // `invoke` returns a Promise
  .then((response) => {
    console.log(response)
  })

window.TAURI_INVOKE.invoke is undefined 问题

tauri.conf.json添加withGlobalTauri,值为true

{
  "$schema": "../node_modules/@tauri-apps/cli/schema.json",
  "build": {
    "beforeBuildCommand": "pnpm run build",
    "beforeDevCommand": "pnpm run dev",
    "devPath": "http://localhost:5173",
    "distDir": "../dist",
    "withGlobalTauri": true
  }

参考资料

JavaScript 模块

JavaScript 使用类
JavaScript 模块

Vue 框架

vue-quick-start

Vue Route

Vue Router
Vue Router 是 Vue 官方的客户端路由解决方案。

客户端路由的作用是在单页应用 (SPA) 中将浏览器的 URL 和用户看到的内容绑定起来。当用户在应用中浏览不同页面时,URL 会随之更新,但页面不需要从服务器重新加载。

Vue Router 基于 Vue 的组件系统构建,你可以通过配置路由来告诉 Vue Router 为每个 URL 路径显示哪些组件。

vite

vite
在浏览器支持 ES 模块之前,JavaScript 并没有提供原生机制让开发者以模块化的方式进行开发。这也正是我们对 “打包” 这个概念熟悉的原因:使用工具抓取、处理并将我们的源码模块串联成可以在浏览器中运行的文件。

时过境迁,我们见证了诸如 webpack、Rollup 和 Parcel 等工具的变迁,它们极大地改善了前端开发者的开发体验。

然而,当我们开始构建越来越大型的应用时,需要处理的 JavaScript 代码量也呈指数级增长。包含数千个模块的大型项目相当普遍。基于 JavaScript 开发的工具就会开始遇到性能瓶颈:通常需要很长时间(甚至是几分钟!)才能启动开发服务器,即使使用模块热替换(HMR),文件修改后的效果也需要几秒钟才能在浏览器中反映出来。如此循环往复,迟钝的反馈会极大地影响开发者的开发效率和幸福感。

Vite 旨在利用生态系统中的新进展解决上述问题:浏览器开始原生支持 ES 模块,且越来越多 JavaScript 工具使用编译型语言编写。

Nuxt

Nuxt是一个免费且开源的框架,它提供了一种直观且可扩展的方式来创建类型安全、高性能和生产级别的全栈Web应用和网站,使用的是Vue.js。
我们做了一切,让你从一开始就可以编写.vue文件,同时在开发中享受到热模块替换的便利,并在生产中获得高性能的应用,其中默认启用了服务器端渲染。

gitignore文件

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

上传到csdn gitcode

网站端

首先在gitcode站点新建项目,如下图所示

在这里插入图片描述
创建完项目,会自动跳转到项目页面,点击SSH,本文采用SSH方式上传项目
在这里插入图片描述

本地端

你还可以按照以下说明从你的电脑中上传现有文件或项目。

cd tauri-app
git init

Git 全局设置

git config --local user.name " 用户名"
git config --local user.email " 用户名@noreply.gitcode.com"

创建一个新仓库

git clone git@gitcode.com: 用户名/tauri-app.git
cd tauri-app
echo# tauri-app” >> README.md
git add README.md
git commit -m “add README”
git branch -m master
git push -u origin master

推送现有的文件

cd existing_folder
git init
git remote add origin git@gitcode.com: 用户名/tauri-app-001.git
git add .
git commit -m “Initial commit”
git branch -m master
git push -u origin master

推送现有的 Git 仓库

cd existing_repo
git remote rename origin old-origin
git remote add origin git@gitcode.com: 用户名/tauri-app.git
git push -u origin --all
git push -u origin --tags

gitcode发布

Git基础 - git tag 一文真正的搞懂git标签的使用

# 创建附注标签
git tag -a v0.0.1 -m "创建tauri V1 应用模板"
# 将指定的标签上传到远程仓库
git push origin v0.0.1

http://www.niftyadmin.cn/n/5664615.html

相关文章

电池管理仓的拆解

拆解视频里面可以学习到大厂的设计思想和创意&#xff0c;接触到比较行业化的设计方案&#xff0c;从而提升设计电路的水平。 电池仓&#xff1a; 电池管家的芯片用的就是前段时间了解到的STM32G030C8T6&#xff0c;便宜好用的典范&#xff1a; 弧形走线较为推荐&#xff1a; …

SpringCloud解读

在Java中&#xff0c;Spring Cloud是一个基于Spring Boot的一站式企业级分布式应用开发框架。它整合了多种分布式系统的常见模式&#xff0c;如配置管理、服务发现、断路器、智能路由、微代理、控制总线等&#xff0c;使得开发者能够轻松地构建分布式系统。Spring Cloud的核心组…

C语言17--条件编译

条件编译 概念&#xff1a;有条件的编译&#xff0c;通过判断某些宏的值&#xff0c;来决定编译哪段代码&#xff08;选择性使用某一段代码&#xff09;。判断宏的值是否为真&#xff1a; 形式1&#xff1a;判断表达式 MACRO 是否为真&#xff0c;据此决定其所包含的代码段是否…

tidb 集群搭建

官网的搭建文档&#xff1a;使用 TiUP 部署 TiDB 集群 | TiDB 文档中心 我本地使用三台 centos7.9 服务器搭建&#xff0c;要保证三台服务器之间是可以互相通信的&#xff1b; 搭建集群的命令在其中一台服务器上执行即可&#xff1b; 1、安装tiup&#xff1a; curl --proto …

iKuai使用及设置流程

iKuai使用及设置流程 iKuai安装步骤 一、配置主机 1.电脑连接ETH0网口 2.ETH1网口连接猫上面的千兆口 3.手动配置pc的IP地址和192.168.1.1./24在同一网段 3.浏览器输入192.168.1.1 admin admin 二、外网设置 1.直接联通电信网络设置 2.点击 网络设置-内外网设置-点击接…

现在量化中普遍使用QMT和PTrade?哪家可以同时提供QMT/PTrade?

QMT的特点 全面的功能集成&#xff1a; QMT集成了行情显示、策略研究、交易执行和风控管理于一体&#xff0c;为投资者提供了一站式的量化交易解决方案。 高效的交易执行能力&#xff1a; 通过全内存交易实现低延迟的交易执行&#xff0c;单笔延时小于1ms&#xff0c;确保了交易…

如何在windows中使用mac,要详细的教程

在 Windows 上运行 macOS 需要使用虚拟机软件。以下是一个详细的教程&#xff0c;展示如何在 Windows 上安装和运行 macOS&#xff1a; 前提条件 硬件要求&#xff1a; 64 位处理器&#xff0c;支持虚拟化技术&#xff08;VT-x 或 AMD-V&#xff09;。至少 8GB 内存&#xff0…

MySQL高阶1777-每家商店的产品价格

题目 找出每种产品在各个商店中的价格。 可以以 任何顺序 输出结果。 准备数据 create database csdn; use csdn;Create table If Not Exists Products (product_id int, store ENUM(store1, store2, store3), price int); Truncate table Products; insert into Products …