Skip to content

Tauri 2.0 介绍与 Vue3 + Vite 客户端开发指南

一、Tauri 2.0 简介

Tauri 是一个跨平台桌面应用开发框架,特点:

  • ✅ 基于 Rust 构建,安全性高
  • 🚀 二进制文件体积小(相比 Electron)
  • 🌐 使用系统原生 WebView 渲染(无需打包浏览器内核)
  • 📱 支持 Windows/macOS/Linux/Android/iOS(2.0 新增移动端支持)
  • 💡 原生 API 集成能力

新特性:

  • 移动端开发支持(Beta)
  • 改进的插件系统
  • 增强的 CLI 工具
  • 更好的 TypeScript 支持

二、开发环境准备

  1. 安装必要工具:

    bash
    # 安装 Rust
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    
    # 安装依赖(macOS)
    brew install python cmake
    
    # 安装 Tauri CLI
    cargo install tauri-cli
  2. 确认版本:

    bash
    rustc --version  # ≥1.70
    node --version   # ≥18

三、创建项目

  1. 初始化 Vue3 项目:

    bash
    npm create vite@latest tauri-demo -- --template vue-ts
    cd tauri-demo
    npm install
  2. 添加 Tauri 依赖:

    bash
    npm install @tauri-apps/api
  3. 初始化 Tauri:

    bash
    npm run tauri init

    按提示填写配置信息

四、配置调整

  1. tauri.conf.json 关键配置:

    json
    {
      "build": {
        "distDir": "../dist",
        "devPath": "http://localhost:5173",
        "beforeDevCommand": "npm run dev",
        "beforeBuildCommand": "npm run build"
      },
      "tauri": {
        "allowlist": {
          "dialog": { "all": true },
          "fs": { "writeFile": true }
        },
        "windows": [{
          "title": "Tauri Demo",
          "width": 800,
          "height": 600
        }]
      }
    }
  2. vite.config.ts 添加配置:

    ts
    export default defineConfig({
      server: {
        strictPort: true,
        hmr: {
          protocol: 'ws',
          host: 'localhost'
        }
      }
    })

五、示例代码

  1. 添加系统对话框功能(App.vue):
    vue
    <script setup lang="ts">
    import { save } from '@tauri-apps/api/dialog';
    import { writeTextFile } from '@tauri-apps/api/fs';
    
    const saveFile = async () => {
      const path = await save({
        filters: [{ name: 'Text', extensions: ['txt'] }]
      });
      
      if (path) {
        await writeTextFile(path, 'Hello Tauri!');
        alert('File saved!');
      }
    };
    </script>
    
    <template>
      <div class="container">
        <h1>Tauri 2.0 + Vue3</h1>
        <button @click="saveFile">保存文件</button>
      </div>
    </template>

六、运行与构建

  1. 开发模式:

    bash
    npm run tauri dev
  2. 生产构建:

    bash
    npm run tauri build
  3. 移动端构建(Android):

    bash
    npm run tauri android init
    npm run tauri android dev

提示:访问 Tauri 官方文档 获取完整 API 参考