Now Reading
Tauri Cellular – Develop cell apps with JavaScript and Rust

Tauri Cellular – Develop cell apps with JavaScript and Rust

2023-03-01 02:08:32

Studio Terabyte is a fullstack web development studio who finds and builds solutions that fit your project

Tauri describes itself as a framework for building tiny, blazingly fast binaries for all major desktop platforms. Developers can integrate any front-end framework that compiles to HTML, JS and CSS for building their user interface. The backend of the application is a rust-sourced binary with an API that the front-end can interact with.

So, Tauri is a framework which allows you to build cross-platform apps using technologies you are already familiar with. And now it also supports mobile apps. Sounds great, doesn’t it

Now, why would you use something like Tauri instead of Kotlin for Android apps and Swift for iOS apps? Before everything it lets you work with applied sciences you’re already aware of. Not being pressured to be taught an entire new programming language, to not point out your entire toolchain the language requires, is an enourmouse time safer. It additionally makes it simple to increase your present internet app into the cell app area with out having to rent devoted engineers.

Besides those reason, others to consider are:

  • Security
  • FLOSS
  • Bundle Size
  • Performance
  • Plugin System
  • Self Updater

*Note: This is based on the 2.0 Alpha version and the early version of the documentation. An update version of the create-tauri-app utility is in growth to make quite a lot of the next steps simpler. That being mentioned, understanding the fundamentals is at all times helpfull!

The basics

First, ensure that you have all the prerequists installed needed for the mobile app development. I’m working on a mac and building and iOS app, so I’m following the instructions here. In case you use a distinct OS or wish to goal Android, you can begin here as an alternative.

Now that we have the basics ready, let’s start by installing the Tauri create-tauri-app Rust utility. This may enable us to simply initialize a brand new Tauri mission. I’m going for a Vue and TypeScript mission.

cargo install create-tauri-appcargo create-tauri-app

Now cd into the brand new folder that was created and ensure that we’re on the latest model. First, run the next command

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

Great, that was the Node part! Now cd into the src-tauri folder and run the next instructions to replace the Rust half:

cargo add tauri@2.0.0-alpha.0cargo add tauri-build@2.0.0-alpha.0 --buildcargo install tauri-cli --version "^2.0.0-alpha"

We are getting ready to develop our mobile app! To develop mobile Tauri applications, the frontend must serve the assets listening on your public network address. The network address can be found using the internal-ip NPM package. You can install it with the following command:

npm install --save-dev internal-ip

Configuration updates

Next, we need to update the vite.config.ts file. I am utilizing Vue so mine appears like this:

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 choices tailor-made for Tauri growth and solely utilized in `tauri dev` or `tauri construct`  // forestall vite from obscuring rust errors  clearScreen: false,    server: {      host: '0.0.0.0', // hear on all addresses      port: 5173,      strictPort: true,      hmr: {        protocol: 'ws',        host,        port: 5183,      },    },  // to utilize `TAURI_DEBUG` and different env variables  // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand  envPrefix: ["VITE_", "TAURI_"],  construct: {    // Tauri helps es2021    goal: course of.env.TAURI_PLATFORM == "home windows" ? "chrome105" : "safari13",    // do not minify for debug builds    minify: !course of.env.TAURI_DEBUG ? "esbuild" : false,    // produce sourcemaps for debug builds    sourcemap: !!course of.env.TAURI_DEBUG,  },  }  return config})

If you use a different framework, make sure to keep the framework-specific plugins that were already in this file.

One more configuration update. This is an important one!

Update tauri.conf.json:

There are two things that we need to change here. First, add the following object within the bundle object like so:

    "bundle": {
      "active": true,
      "category": "DeveloperTool",
      "copyright": "",
      "deb": {
        "depends": []
      },
      "externalBin": [],
      "iOS": {
        "developmentTeam": "demo"
      },
      "icon": [

Also change the port that Tauri is listening to so that it matches the one your JS framework will be running. In my case it’s 5173. So like this:

  "build": {
    "beforeDevCommand": "npm run dev",
    "beforeBuildCommand": "npm run build",
    "devPath": "http://localhost:5173", <- Here
    "distDir": "../dist",
    "withGlobalTauri": false
  },

Rust changes

Now that the config files are ready, let’s make some changes to our Rust files.

  1. Update your src-tauri/Cargo.toml file with the next line:

[lib]crate-type = ["staticlib", "cdylib", "rlib"]

    See Also

  1. Create a new src-tauri/src/lib.rs file and add the next content material:

use tauri::App;#[cfg(mobile)]mod cell;#[cfg(mobile)]pub use cell::*;pub kind SetupHook = Field<dyn FnOnce(&mut App) -> End result<(), Field<dyn std::error::Error>> + Ship>;#[tauri::command]fn greet(title: &str) -> String {    format!("Hiya, {}!", title)}#[derive(Default)]pub struct AppBuilder {    setup: Choice<SetupHook>,}impl AppBuilder {    pub fn new() -> Self {        Self::default()    }    #[must_use]    pub fn setup<F>(mut self, setup: F) -> Self    the place        F: FnOnce(&mut App) -> End result<(), Field<dyn std::error::Error>> + Ship + 'static,    {        self.setup.substitute(Field::new(setup));        self    }    pub fn run(self) {        let setup = self.setup;        tauri::Builder::default()            .setup(transfer |app| {                if let Some(setup) = setup {                    (setup)(app)?;                }                Okay(())            })            .invoke_handler(tauri::generate_handler![greet])            .run(tauri::generate_context!())            .anticipate("error whereas working tauri software");    }}#[cfg(mobile)]fn do_something() {    println!("Hiya from Cellular!");}#[cfg(desktop)]fn do_something() {    println!("Hiya from Desktop!");}fn run() {    if cfg!(cell) {        println!("Hiya from Cellular!");    } else {        println!("Hiya from Desktop!");    }}

  1. Create a new src-tauri/src/mobile.rs file and add the next content material:

#[tauri::mobile_entry_point]fn most important() {  tremendous::AppBuilder::new().run();}

This is an important step

  1. Update the content of src-tauri/src/main.rs to:

#![cfg_attr(
  all(not(debug_assertions), target_os = "windows"),
  windows_subsystem = "windows"
)]

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

Now that this has been taken care off, finish off with the following steps:

  • run cargo tauri ios init in the principle folder.

    • if you get an error regarding cocaopods, run: brew install cocoapods and check out once more

  • run cargo tauri ios dev to start out the server

Result

Congrats! You should now be asked in which emulator you want your app to run and see something like this:

Iphone 14 Simulator Vite

In this blog post we’ve setup a minimal Tauri app which allows us to build native iOS app using JS, Vue in our case, and Rust!

From here you should have a solid base to build out your own ideas and launch the amazing app you’ve always wanted to build!

You can find the code for this article here: GitHub

Source Link

What's Your Reaction?
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0
View Comments (0)

Leave a Reply

Your email address will not be published.

2022 Blinking Robots.
WordPress by Doejo

Scroll To Top