0. First half and second half
Tauri Installation, Startup, Packaging and Many Use Cases (Part 1)
Tauri Use Cases (Part 2)
1. Install nvm
Visit the nvm official website to download nvm to manage Node.js
nvm list available
Display the downloadable version and record the latest LTS version
At 19:00 on Monday, February 13, 2023, the latest LTS version is 18.14.0
nvm install 18.14.0
Install the latest LTS version
nvm use 18.14.0
Use the latest LTS version
node -v&&npm -v
to view Node. Current versions of js and npm
npm install --global yarn
install yarn
2. Install the Microsoft C++ build tools
Visit Microsoft's official website to download the build tool, and after checking "Desktop development using C++", 5 items will be automatically checked. Uncheck the
following items and only keep the following two (don't care about the SDK version, Win10 or Win11 is fine, just keep whatever is checked) What, don't tick it yourself)
用于 Windows 的 C++ CMake 工具
测试工具核心功能 - 生成工具
C++ AddressSanitizer
MSVC v143 - VS 2022 C++ x64/x86 生成工具
Windows 11 SDK (10.0.22000.0)
3. Install Rust
The computer must be restarted before installation
Visit Rust official website to download and install Rust
4. Configure mirroring
Run where rustc
to find .cargo
the folder Create a new file without suffix
under .cargo
the folder, the file name is config, and enter the following content, save
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'ustc'
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"
5. Install WebView2
Win11 has pre-installed WebView2 (Win10 should also be updated).
Visit the Microsoft official website to download and install the x64 version of the evergreen version of the standalone installer (you can also download the boot version if you have a good network)
6. Install VSCode
Download and install VSCode
installation plug-ins: Tauri plug-in , rust-analyzer plug-in
7. Modify the PowerShell execution policy
Run PowerShell Get-ExecutionPolicy
, if the result is not, RemoteSigned
modify the execution policy of PowerShell as follows. After
running PowerShell, Set-ExecutionPolicy RemoteSigned
enter A
confirmation, and modify the execution policy of PowerShell
. PowerShell only needs to modify the execution policy once.
8.create-tauri-app vanilla
Note : The default value of the withGlobalTauri setting item in .\tauri-app\src-tauri\tauri.conf.json
the document is set tofalse
true
yarn create tauri-app
Quickly create a new Tauri project.
Project name?
Press Enter directly to skip
Choose your package manager?
yarn
Choose your UI template?
vanilla
and enter the following commands one by one.
cd tauri-app
yarn
yarn tauri dev
Wait for about 5 minutes, and the window appears.
close the window
8.1. Compilation end sound prompt
1. .\tauri-app\src\index.html
Add a sound label to , and there will be a sound reminder when the software starts
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
<audio controls autoplay>
<source src="/assets/easy-lifestyle-137766.mp3" type="audio/mpeg" />
</audio>
</body>
</html>
2. yarn tauri build
Change to yarn tauri build ; echo ^G
(use the shortcut key Ctrl+G
to enter ^G
) (in CMD to change yarn tauri build && echo ^G
)
there will be a system prompt after the package is completed
9. Pack
1. Open .\tauri-app\src-tauri\tauri.conf.json
the file for modification identifier
, add tauri.bundle.windows.wix.language
before modification
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "com.tauri.dev",
"longDescription": "",
After modification (identifier can be changed to anything, just add a not here)
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "notcom.nottauri.notdev",
""
"longDescription": "",
2. Open .\tauri-app\src-tauri\tauri.conf.json
the file and add tauri.bundle.windows.wix.language
before modification
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
}
after modification
"windows": {
"certificateThumbprint": null,
"wix": {
"language": "zh-CN" },
"digestAlgorithm": "sha256",
"timestampUrl": ""
}
3. .\tauri-app
Run in the project directory yarn tauri build
, wait for a long compilation time, and get two files
4. Exe file path without installation: .\tauri-app\src-tauri\target\release\tauri-app.exe
installation package msi file path:.\tauri-app\src-tauri\target\release\bundle\msi\tauri-app_0.0.0_x64_zh-CN.msi
9.1. Because wix cannot download and package failed
The error displayed is as follows
Downloading https://github.com/wixtoolset/wix3/releases/download/wix3112rtm/wix311-binaries.zip
Error failed to bundle project: `TlsError: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。 (os error 10060)`: Tls Error: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。 (os error 10060)
Solution:
Make sure you can connect to Github and try again or open the directory . %LocalAppData%
Manually create the path ( or .\AppData\Local\tauri\WixTools
call %LocalAppData%\tauri\WixTools
)
the wix download address displayed when the copy fails. Use Github mirror station, accelerator, hosts file, Github file download, etc.
Unzip the downloaded compressed package to the newly created path, like this %LocalAppData%\tauri\WixTools\dark.exe
, and then pack it again. WixTools will only be downloaded once
10.main.js
.\tauri-app\src\main.js
// 访问已打包好的全局 API 函数
const {
invoke } = window.__TAURI__.tauri;
// 输入框元素
let greetInputEl;
// 欢迎信息元素
let greetMsgEl;
async function greet() {
// 更多 Tauri commands 移步 Tauri指南,https://tauri.app/zh-cn/v1/guides/features/command/
greetMsgEl.textContent = await invoke("greet", {
name: greetInputEl.value,
});
}
// 当初始HTML文档已完全加载和解析时,向按钮元素添加监听事件。
window.addEventListener("DOMContentLoaded", () => {
greetInputEl = document.querySelector("#greet-input");
greetMsgEl = document.querySelector("#greet-msg");
document
.querySelector("#greet-button")
.addEventListener("click", () => greet());
});
11.main.rs
.\tauri-app\src-tauri\src\main.rs
// https://www.rustwiki.org.cn/zh-CN/reference/conditional-compilation.html?highlight=cfg_attr#cfg_attr%E5%B1%9E%E6%80%A7
// 构建完毕的应用在 Windows 上运行时一般会出现控制台窗口。这段代码表示不显示这个控制台窗口。
// 注释这段代码会显示控制台窗口。
// 将windows_subsystem = "windows"改为windows_subsystem = "console",也会显示控制台窗口。
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
// 更多 Tauri commands 移步 Tauri指南,https://tauri.app/zh-cn/v1/guides/features/command/
// 拥有 #[tauri::command] 宏的函数可以被 JavaScript 调用。
#[tauri::command]
fn greet(name: &str) -> String {
format!("你好, {}!这是来自Rust的问候!", name)
}
// main 函数是所有 Rust 程序的入口点。
fn main() {
// .invoke_handler() 函数配合 generate_handler![] 宏注册指令。
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet])
.run(tauri::generate_context!())
.expect("运行 tauri 应用程序时出错");
}
12. Solve the problem that the Tauri document page is full of black characters and cannot distinguish between primary and secondary
document.querySelectorAll("h2").forEach((i)=>{
i.style = "background-color: tan;"});
document.querySelectorAll("h3").forEach((i)=>{
i.style = "background-color: #d2b48c99;"});
13. Open the developer tools programmatically
main.rs
The modified main
function, run yarn tauri dev
, Devtools window and Tauri window will be displayed at the same time
fn main() {
tauri::Builder::default()
.setup(|app| {
use tauri::Manager;
#[cfg(debug_assertions)] //仅在调试时自动打开开发者工具
{
let main_window = app.get_window("main").unwrap();
main_window.open_devtools();
}
Ok(())
})
.invoke_handler(tauri::generate_handler![greet])
.run(tauri::generate_context!())
.expect("错啦!");
}
14. Get all windows, get your own window
withGlobalTauri
Get the window as long as it is enabled
const tauriWindow = window.__TAURI__.window;
console.log(tauriWindow.getAll());
console.log(tauriWindow.getCurrent());
15. tauri responds to javascript alert
tcfg-alert
main.js
The greet
function: async function greet() { alert(greetInputEl.value); }
tauri.conf.json
: { "tauri": { "allowlist": { "dialog": { "message": true } } } }
yarn tauri dev
, click Greet
the button, a pop-up window will appear
16.rust read file
Follow step 8 to create a new tauri-rust-readfile
project named
1, .\tauri-rust-readfile\src-tauri
run it in the directory cargo add dirs
2, prepare a TextEditor.txt
file and place it on the desktop, and write something casually
1.VSCode
2.SublimeText
3.Kate
3. .\tauri-rust-readfile\src\main.js
Change greet
the function to read_texteditor_file
a function, and modify the listening event of the button element
const {
invoke } = window.__TAURI__.tauri;
let greetInputEl;
let greetMsgEl;
async function read_texteditor_file() {
greetMsgEl.textContent = await invoke("read_texteditor_file");
}
window.addEventListener("DOMContentLoaded", () => {
greetInputEl = document.querySelector("#greet-input");
greetMsgEl = document.querySelector("#greet-msg");
document
.querySelector("#greet-button")
.addEventListener("click", () => read_texteditor_file());
});
4. Similarly, change the function .\tauri-rust-readfile\src-tauri\src\main.rs
of to a function , be careful not to drop thegreet
read_texteditor_file
.invoke_handler(tauri::generate_handler![read_texteditor_file])
read_texteditor_file
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
#[tauri::command]
fn read_texteditor_file() -> String {
let mut textfile = dirs::desktop_dir().expect("找不到桌面路径");
textfile.push("folderfortauri");
textfile.push("TextEditor.txt");
let data = std::fs::read_to_string(textfile);
match data {
Ok(text) => text,
Err(_) => "文件打开失败".to_string(),
}
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![read_texteditor_file])
.run(tauri::generate_context!())
.expect("运行 tauri 应用程序时出错");
}
5. .\tauri-rust-readfile
Run in the project directory yarn tauri dev
Wait for the compilation to complete, the window appears, click Greet
the button, and the file content is successfully read
17.javascript read file
Follow step 8 to create a tauri-js-readfile
new project named
1, read file scope .\tauri-js-readfile\src-tauri\tauri.conf.json
configured in , enable andfs
exists
readfile
{
...
"tauri": {
"allowlist": {
"all": false,
"shell": {
"all": false,
"open": true
},
"fs": {
"exists": true,
"readFile": true,
"scope": ["$DESKTOP/folderfortauri/*"]
}
},
...
...
}
2. Modify.\tauri-js-readfile\src\main.js
const {
invoke } = window.__TAURI__.tauri;
const {
readTextFile, exists, BaseDirectory } = window.__TAURI__.fs;
let greetInputEl;
let greetMsgEl;
async function read_texteditor_file() {
let textfile = "folderfortauri\\TextEditor.txt";
if (await exists(textfile, {
dir: BaseDirectory.Desktop })) {
greetMsgEl.textContent = await readTextFile(textfile, {
dir: BaseDirectory.Desktop,
});
} else {
console.error(textfile + ",该文件不存在!");
greetMsgEl.textContent = textfile + ",该文件不存在!";
}
}
window.addEventListener("DOMContentLoaded", () => {
greetInputEl = document.querySelector("#greet-input");
greetMsgEl = document.querySelector("#greet-msg");
document
.querySelector("#greet-button")
.addEventListener("click", () => read_texteditor_file());
});
3. .\tauri-rust-readfile
Run in the project directory yarn tauri dev
, click Greet
the button, and successfully read the file content
allowlistconfig - tauri document , the second item is fs
( window.__TAURI__.fs
)
fs security settings - tauri document
BaseDirectory - tauri document
fsallowlistscope - tauri document
CSIDL - Microsoft
KNOWNFOLDERID - Microsoft
https://tauri.app/zh-cn/v1/api/js/path
Config %APPDATA%
AppConfig %APPDATA%\com.tauri.dev
Data %APPDATA%
AppData %APPDATA%\com.tauri.dev
Log %APPDATA%\com.tauri.dev\logs(即将废弃,会被AppLog取代)
AppLog %APPDATA%\com.tauri.dev\logs
LocalData %LOCALAPPDATA%
AppLocalData %LOCALAPPDATA%\com.tauri.dev
Cache %LOCALAPPDATA%
AppCache %LOCALAPPDATA%\com.tauri.dev
Home %LocalAppdata%\com.tauri.dev
Audio %USERPROFILE%\Music
Desktop %USERPROFILE%\Desktop
Document %USERPROFILE%\Documents
Download %USERPROFILE%\Downloads
Picture %USERPROFILE%\Pictures
Video %USERPROFILE%\Videos
Public %PUBLIC%
Resource \\?\D:\tauri-js-readfile\src-tauri\target\debug(不知道\\?\是什么意思)
App %APPDATA%\com.tauri.dev(即将废弃,会被AppConfig和appDataDir取代)
Temp 通常是%USERPROFILE%\AppData\Local\Temp
Template %APPDATA%\Microsoft\Windows\Templates;Linux: xdg-user-dirs' XDG_TEMPLATES_DIR;不支持macOS
Font 不支持Windows;Linux: $XDG_DATA_HOME/fonts or $HOME/.local/share/fonts;macOS: $HOME/Library/Fonts
Runtime 仅支持Linux: $XDG_RUNTIME_DIR
Executable 仅支持Linux: $XDG_BIN_HOME/../bin or $XDG_DATA_HOME/../bin or $HOME/.local/bin
scope
Should be set as a list, containing one or more paths, similar to the following
"scope": ["$DESKTOP/folderfortauri/*"]
// 或者
"scope": ["$TEMP/tauri_temp/*", "$APPDATA/databases/*"]
18.javaScript dynamically creates new windows
Follow step 8 to create a new tauri-js-openwindow2
project named
edit .\tauri-js-openwindow2\src-tauri\tauri.conf.json
, add tauri.allowlist.window.create
, set totrue
{
...
"tauri": {
"allowlist": {
"all": false,
"shell": {
"all": false,
"open": true
},
"window": {
"create": true
}
},
...
}
}
Editing function .\tauri-js-openwindow2\src\main.js
_greet
async function greet() {
const {
WebviewWindow } = window.__TAURI__.window;
const webview = new WebviewWindow("w2", {
url: "https://tauri.app/zh-cn/v1/guides/features/multiwindow#%E5%9C%A8-javascript-%E4%B8%AD%E5%88%9B%E5%BB%BA%E7%AA%97%E5%8F%A3",
});
// 由于 webview 窗口是异步创建的,
// 窗口创建成功会调用 `tauri://created`
// 窗口创建失败会调用 `tauri://error`
webview.once("tauri://created", function () {
console.log("创建窗口成功");
});
webview.once("tauri://error", function (e) {
console.error("创建窗口失败: " + e.payload);
console.log(e);
});
}
Run yarn tauri dev
, click Greet
the button
window configuration in tauri.conf.json
WindowAllowlistConfig
19. Static multi-window, javaScript controls the display and hiding of windows
Follow step 8 to create tauri-config-staticwindow
project
1, modify the .\tauri-config-staticwindow\src-tauri\tauri.conf.json
added , , add two , onetauri.allowlist.window
show
hide
label
visible
{
...
"tauri": {
"allowlist": {
"all": false,
"shell": {
"all": false,
"open": true
},
"window":{
"show": true,
"hide": true
}
},
...
"windows": [
{
"label": "w1",
"fullscreen": false,
"height": 600,
"resizable": true,
"title": "tauri-config-staticwindow",
"width": 800
},
{
"label": "w2",
"visible": false
}
]
}
}
2. .\tauri-config-staticwindow\src\main.js
Modified greet
function
let w2_isshow = false;
async function greet() {
const {
WebviewWindow } = window.__TAURI__.window;
const w2 = WebviewWindow.getByLabel("w2");
w2_isshow ? w2.hide() : w2.show();
w2_isshow = !w2_isshow;
}
3. Run yarn tauri dev
and click the button of the "tauri-config-staticwindow" window several times Greet
to successfully display and hide the new window
20.rust dynamically creates new windows
Follow step 8 to create tauri-rust-openwindow2
project
1. Change the function .\tauri-rust-openwindow2\src-tauri\src\main.rs
of greet
function to function Be careful not to drop the open_docs
functiontauri::generate_handler![open_docs]
open_docs
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
// javaScript 使用 open_docs 函数时并不需要 handle 参数
// 命令可以访问调用消息的```Window```实例和```AppHandle```实例,tauri不会让js感知到这两个参数的存在
#[tauri::command]
async fn open_docs(handle: tauri::AppHandle) {
let doc_url = "https://tauri.app/zh-cn/v1/guides/features/multiwindow";
let _docs_window = tauri::WindowBuilder::new(
&handle,
"doc",
tauri::WindowUrl::External(doc_url.parse().unwrap()),
)
.build()
.unwrap();
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![open_docs])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
2. The function command .\tauri-rust-openwindow2\src\main.js
in editing can access the instance and instance of the calling message, tauri will not let js perceive the existence of these two parametersgreet
Window
AppHandle
async function greet() {
greetMsgEl.textContent = await invoke("open_docs", {
/*!!没有参数!!*/
});
document.querySelector("#greet-button").disabled = true;
}
3. You can also add some css, edit .\tauri-rust-openwindow2\src\style.css
, and button:hover
add the following content below
button:hover {
border-color: #396cd8;
}
button:disabled {
border: 1px solid #999999;
background-color: #cccccc;
color: #666666;
text-decoration: line-through;
}
button:disabled:hover {
cursor: not-allowed;
}
4. Run yarn tauri dev
, click Greet
the button, and successfully display a new window
98.yarn tauri dev error failed to download
error: failed to download from `https://crates-io.proxy.ustclug.org/api/v1/crates/http/0.2.9/download`
Mirror image convulsions, change to other images, byte mirroring , University of Science and Technology of China , Shanghai Jiaotong University , Tsinghua University
99. Other
1. , F12
, Ctrl+Shift+I
can 右键-检查
open DevTools, which is disabled by default after packaging. To enable DevTools, you can refer to: ① Manually enable the development tool function , ② yarn tauri build --debug
, ③ Eruda
2. To end the Tauri program, confirm that the command line has ended (or use --no-watch
parameters, Ctrl+C
force the end command), and then modify the code, otherwise Tauri will compile first, The window jumps out to scare you. Files that don't need to be compiled (for example html
) will work immediately.
3. Tauri cannot use Node.js , unless the sidecar function is used
4. The project name is best to follow the snake-like nomenclature, so as not to report a warning after compiling 5. The closure syntax
in Tauri belongs to Rust|app|
100. Documentation
Take the first step with Rust - Microsoft learns
Rust by example Rust
practice field, run online
Rust reference manual Chinese version , Rust language study notes , Rust study notes , RustPrimer , Rust online tutorial
Tauri Guide , Tauri Documentation , Tauri Events , Tauri Features , Tauri API
GitHub Discussions - Tauri Series