插件生态系统
插件生态系统
Section titled “插件生态系统”Tauri v2 采用了模块化架构。为了保持核心应用程序的轻量和安全,许多以前内置的功能(或你可能期望从 Electron 获得的功能)现在都已分离为插件(plugins)。这确保你只打包你实际使用的功能的代码。
插件工作原理
Section titled “插件工作原理”使用插件通常涉及三个步骤:
- 安装:通过
cargo添加 Rust crate,并通过你的包管理器(npm/pnpm/yarn)添加 JavaScript API。 - 注册:在你的 Rust
lib.rs构建器链中初始化插件。 - 使用:在你的前端导入 JavaScript API 以使用其功能。
持久化设置:Store 插件
Section titled “持久化设置:Store 插件”plugin-store 允许你将简单的键值数据(key-value data),如用户偏好设置(user preferences)或应用程序状态(application state),保存到磁盘文件中。它会自动处理序列化(serialization)。
import { Store } from '@tauri-apps/plugin-store';
const store = new Store('settings.json');
// Set a value// 设置一个值await store.set('theme', 'dark');
// Save changes to disk// 将更改保存到磁盘await store.save();
// Retrieve a value// 检索一个值const val = await store.get('theme');文件系统访问:FS 插件
Section titled “文件系统访问:FS 插件”plugin-fs 插件提供了文件系统(file system)访问功能。与标准浏览器 API(browser APIs)不同,它允许你在操作系统权限(OS permissions)允许的任何位置读写文件(为安全起见进行了作用域限定)。
import { readTextFile, writeTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
// Write to the App Data directory// 写入应用程序数据目录await writeTextFile('app.conf', 'config_data', { baseDir: BaseDirectory.AppData});
// Read the file back// 读取文件内容const content = await readTextFile('app.conf', { baseDir: BaseDirectory.AppData});网络:HTTP 插件
Section titled “网络:HTTP 插件”尽管 fetch 在浏览器中可用,但它受到 CORS(Cross-Origin Resource Sharing,跨域资源共享)的限制。plugin-http 允许你的 Rust 后端(Rust backend)执行请求,完全绕过 CORS 问题,这对于调用第三方 API(third-party APIs)至关重要。
本地数据库:SQL 插件
Section titled “本地数据库:SQL 插件”对于更复杂的数据需求,plugin-sql 提供了与 SQLite、MySQL 或 PostgreSQL 的连接。SQLite 特别受本地桌面应用(local desktop apps)欢迎,因为它无需服务器设置(server setup)。
import Database from '@tauri-apps/plugin-sql';
const db = await Database.load('sqlite:test.db');
await db.execute('INSERT INTO users (name) VALUES ($1)', ['Alice']);插件是构建丰富 Tauri 应用程序的基石,它允许你扩展功能而不会使你的应用程序核心变得臃肿。