Tauri Mobile-使用JavaScript和Rust开发移动应用程序

1. 前言

Tauri 定位为一个为所有主要桌面平台构建微小、速度极快的二进制文件的框架。开发人员可以集成任何可编译为 HTML、JS 和 CSS 的前端框架来构建用户界面。应用程序的后端是一个 Rust 二进制文件,具有前端可以与之交互的 API。

因此,Tauri 是一个框架,允许您使用您已经熟悉的技术构建跨平台应用程序。现在它还支持移动应用程序。听起来很棒,不是吗?

2. 为什么使用 Tauri

现在,为什么要使用像 Tauri 这样的东西而不是 KotlinAndroid 应用程序和 SwiftiOS 应用程序呢?首先也是最重要的是,它允许您使用您已经熟悉的技术。不必被迫学习全新的编程语言,更不用说该语言所需的整个工具链,这会安全得多。它还可以轻松地将您当前的 Web 应用程序扩展到移动应用程序领域,而无需雇用专门的工程师。

除了这些原因之外,其他需要考虑的因素还有:

安全
是否开源免费(FLOSS)
Bundle 尺寸
性能
插件体系
自我更新器

3. 最小的 Tauri 移动应用程序

该应用是基于 2.0 Alpha 版本和 2.0 版本的早期文档。该实用程序的更新版本 create-tauri-app 正在开发中,以使以下许多步骤变得更加容易。话虽这么说,了解基础知识总是有帮助的!

3.1. 开发环境

首先,确保您已安装移动应用程序开发所需的所有先决条件。我正在 Mac 上工作并构建 iOS 应用程序,因此我按照此处的说明进行操作。如果您使用不同的操作系统或想要以 Android 为目标,则可以从这里开始。

现在我们已经准备好了开发环境,让我们开始安装 Tauri create-tauri-appRust 实用程序。这将使我们能够轻松初始化一个新的 Tauri 项目。我将要创建一个 Vue 项目并使用 TypeScript 开发。

1
2
3
4
5

cargo install create-tauri-app

cargo create-tauri-app

现在 cd 进入新创建的文件夹,并确保我们使用的是最新版本。首先,运行以下命令.

1
npm install @tauri-apps/cli@next @tauri-apps/api@next

这就是 Node 部分需要做的事情.现在 cd 进入该 src-tauri 文件夹并运行以下命令来更新 Rust 部分:

1
2
3
4
5
cargo add tauri@2.0.0-alpha.0

cargo add tauri-build@2.0.0-alpha.0 --build

cargo install tauri-cli --version "^2.0.0-alpha"

我们已经准备好开发我们的移动应用程序了!要开发移动 Tauri 应用程序,前端必须在您的公共网络地址监听并提供服务。可以使用 internal-ip npm 包找到网络地址。您可以使用以下命令安装它:

1
npm install --save-dev internal-ip

4. 修改配置文件

接下来,我们需要更新该 vite.config.ts 文件。我正在使用 Vue,所以我的看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { defineConfig } from "vite";
import { internalIpV4 } from "internal-ip";
import vue from "@vitejs/plugin-vue";

export default defineConfig(async () => {
const host = await internalIpV4();

/** @type {import('vite').UserConfig} */
const config = {
plugins: [vue()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
// prevent vite from obscuring rust errors
clearScreen: false,
server: {
host: "0.0.0.0", // listen on all addresses
port: 5173,
strictPort: true,
hmr: {
protocol: "ws",
host,
port: 5183,
},
},
// to make use of `TAURI_DEBUG` and other env variables
// https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
envPrefix: ["VITE_", "TAURI_"],
build: {
// Tauri supports es2021
target:
process.env.TAURI_PLATFORM == "windows" ? "chrome105" : "safari13",
// don't minify for debug builds
minify: !process.env.TAURI_DEBUG ? "esbuild" : false,
// produce sourcemaps for debug builds
sourcemap: !!process.env.TAURI_DEBUG,
},
};

return config;
});

如果您使用不同的框架,请确保保留此文件中特定于框架的插件。

更新 tauri.conf.json, 这很重要!

这里有两件事我们需要改变。第一,在 bundle 对象中添加以下对象,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
"bundle": {
"active": true,
"category": "DeveloperTool",
"copyright": "",
"deb": {
"depends": []
},
"externalBin": [],
"iOS": {
"developmentTeam": "demo"
},
"icon": [

还要更改 Tauri 正在侦听的端口,使其与您的 JS 框架将运行的端口相匹配。就我而言,它是 5173. 像这样:

1
2
3
4
5
6
7
"build": {
"beforeDevCommand": "npm run dev",
"beforeBuildCommand": "npm run build",
"devPath": "http://localhost:5173", <- Here
"distDir": "../dist",
"withGlobalTauri": false
},

5. 修改 Rust 代码

现在配置文件已准备就绪,让我们对 Rust 文件进行一些更改。

  • src-tauri/Cargo.toml 更新如下:

    1
    2
    [lib]
    crate-type = ["staticlib", "cdylib", "rlib"]
  • 创建一个新 src-tauri/src/lib.rs 文件并添加以下内容:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    use tauri::App;

    #[cfg(mobile)]
    mod mobile;
    #[cfg(mobile)]
    pub use mobile::*;

    pub type SetupHook = Box<dyn FnOnce(&mut App) -> Result<(), Box<dyn std::error::Error>> + Send>;

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

    #[derive(Default)]
    pub struct AppBuilder {
    setup: Option<SetupHook>,
    }

    impl AppBuilder {
    pub fn new() -> Self {
    Self::default()
    }

    #[must_use]
    pub fn setup<F>(mut self, setup: F) -> Self
    where
    F: FnOnce(&mut App) -> Result<(), Box<dyn std::error::Error>> + Send + 'static,
    {
    self.setup.replace(Box::new(setup));
    self
    }

    pub fn run(self) {
    let setup = self.setup;
    tauri::Builder::default()
    .setup(move |app| {
    if let Some(setup) = setup {
    (setup)(app)?;
    }
    Ok(())
    })
    .invoke_handler(tauri::generate_handler![greet])
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
    }
    }

    #[cfg(mobile)]
    fn do_something() {
    println!("Hello from Mobile!");
    }

    #[cfg(desktop)]
    fn do_something() {
    println!("Hello from Desktop!");
    }

    fn run() {
    if cfg!(mobile) {
    println!("Hello from Mobile!");
    } else {
    println!("Hello from Desktop!");
    }
    }
  • 创建一个新 src-tauri/src/mobile.rs 文件并添加以下内容:

    1
    2
    3
    4
    #[tauri::mobile_entry_point]
    fn main() {
    super::AppBuilder::new().run();
    }

    这是重要的一步

  • 将内容更新 src-tauri/src/main.rs 为:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
    )]

    pub fn main() {
    // Change demo_mobile_app to the name of your app!
    demo_mobile_app::AppBuilder::new().run();
    }

现在这已经解决了,请完成以下步骤:

cargo tauri ios init 在主文件夹中运行。

如果您收到有关 cocoapods 的错误,请运行:brew install cocoapods 然后重试

运行 cargo tauri ios dev 以启动服务器

6. 结果

恭喜!现在应该询问您希望应用程序在哪个模拟器中运行.

7. 关联阅读

升级App到Tauri 2.0并配置Tauri Mobile

创建 gitlab pipeline 打包 Tauri 跨平台应用程序

Tauri cli 详解

在 Linux 上配置 Tauri 环境

使用 Tauri 和 Angular 创建桌面应用程序

Tauri 开发环境配置

Tauri Mobile-使用 JavaScript 和 Rust 开发移动应用程序

8. 结论

在这篇博文中,我们设置了一个最小的 Tauri 应用程序,它允许我们使用 JS、Vue(在我们的例子中)和 Rust 构建可安装的 iOS 应用程序!
从这里开始,您应该拥有坚实的基础来构建自己的想法并启动您一直想要构建的令人惊叹的应用程序!
您可以在这里找到本文的代码:GitHub