Tauri 介绍
Build an optimized, secure, and frontend-independent application for multi-platform deployment.(为多平台部署构建优化、安全且独立于前端的应用程序。)
特点
多语言
- Rust
- JavaScript/TypeScript
- HTML
- CSS
优点
- 安全
- 较 Electron 小
- webview2 指出
- ...
安装 Rust
windows:
-
使用 Rust 下载器(
.exe
) -
WSL 使用:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
- Visual Studio C++ Build tools
Unix/Linux:
curl https://sh.rustup.rs -sSf | sh
安装 Tauri Cli
cargo/npm 两种包管理:
# cargo
cargo install tauri-cli --version "^1.0.0"
# npm/yarn/pnpm
npm install --save-dev @tauri-apps/cli
yarn add -D @tauri-apps/cli
pnpm add -D @tauri-apps/cli
添加到 package.json
{
"scripts": {
"tauri": "tauri"
}
}
创建项目 cli
npm create tauri-app # npm
yarn create tauri-app # yarn
pnpm create tauri-app # pnpm
集成了各种主流的 JS 脚手架工具,使用起来其实很熟悉,这里选择了 vite + React + TS 的构建方式。
中间会提示: @tauri-apps/api
这里添加 @tauri-apps/api,这些 API 能与系统交互。选择完毕之后,cli 会自动安装 npm 包。下面是 cli 生成的代码:
与传统的 前端项目的不同
- 目录 src/
- 目录 src-tauri
运行项目
cd demo01 # work dir
npm run tarui dev # 启动 cargo 编辑/npm 编译
修改端口
react 脚手架创建的项目使用 3000 端口,很多时候可能这个端口已经被占用了,需改端口:
- tauri.conf.json
"build": {
"beforeBuildCommand": "npm run build",
"beforeDevCommand": "npm run dev",
"devPath": "http://localhost:3333",
"distDir": "../dist"
},
- package.json
"scripts": {
"dev": "vite --port 3333",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
重新启动
npm run tarui dev # 启动 cargo 编辑/npm 编译
构建
npm run tauri build
使用 @tauri-app/api
// 全部导入
import * as apis from "@tauri-apps/api"
// 局部导入
import { path, fs } from "@tauri-apps/api"
输出源码:
import 'regenerator-runtime/runtime';
import * as app from './app';
import * as cli from './cli';
import * as clipboard from './clipboard';
import * as dialog from './dialog';
import * as event from './event';
import * as fs from './fs';
import * as globalShortcut from './globalShortcut';
import * as http from './http';
import * as notification from './notification';
import * as path from './path';
import * as process from './process';
import * as shell from './shell';
import * as tauri from './tauri';
import * as updater from './updater';
import * as window from './window';
import * as os from './os';
/** @ignore */
declare const invoke: typeof tauri.invoke;
export { app, cli, clipboard, dialog, event, fs, globalShortcut, http, notification, path, process, shell, tauri, updater, window, os, invoke };
一个通知使用 notification
<button
onClick={() => {
notification.sendNotification({
title: "TAURI",
body: "Tauri is awesome!",
});
}}
>
notification
</button>
小结
熟悉 Rust,JS 技术栈的体验因该是良好的,以后估计这样多语言的构建方式,会更多...
参考
- Tauri 官方网站 (tauri.app/)
- Rust crates Tauri (docs.rs/tauri/1.0.0…)
- Tauri Cli (tauri.app/v1/api/cli)
- Tauri JavaScript Api (tauri.app/v1/api/js/)
- Tauri 代码仓库 (github.com/tauri-apps/…)
- Rust 安装 (www.rust-lang.org/tools/insta…)
- Edge 浏览器 Webview2 了解(docs.microsoft.com/zh-cn/micro…)
- Electron (www.electronjs.org/)