Tauri: a tool with JS/HTML/CSS & Rust

Profile picture of MikeHe-creator

Draft

Dec 4, 2023

·

6 min read

·

523 Views


I read an artcle that introudces a fronted tool to help you contructed the most saftest web app. This is Tauri. Tauri's core is Rust , and it also need Javascript/html/css to design the UI. Becuase Rust is a very hard language to learn, so this tool is not easy to use for an ordinary fronted programmer. But Rust is said the safest language, so Tauri is regraded as the saftest frontend tool. Here is the installtaion and simple contruction steps to build a frontend app.

1. Installation

Installation is very easy and simple. The installation is very similar with vue, using npm , following its step.

npm create tauri-app@latest 

After the finished, you will see the pic1. This is the model. You can modify the model to design UI. it's very simair with vue.

2.Create a project

At the heart of every Tauri app is a Rust binary that manages windows, the webview, and calls to the operating system through a Rust crate called tauri. This project is managed by Cargo, the official package manager and general-purpose build tool for Rust.

Our Tauri CLI uses Cargo under the hood so you rarely need to interact with it directly. Cargo has many more useful features that are not exposed through our CLI, such as testing, linting, and formatting, so please refer to their official docs for more.

INSTALL TAURI CLI

If you haven't installed the Tauri CLI yet you can do so with one of the below commands.

npm install --save-dev @tauri-apps/cli

For npm to detect Tauri correctly you need to add it to the "scripts" section in your package.json file:

package.json

"scripts": {   "tauri": "tauri" }

To scaffold a minimal Rust project that is pre-configured to use Tauri, open a terminal and run the following command:

npm run tauri init

It will walk you through a series of questions:

  1. What is your app name?
    This will be the name of your final bundle and what the OS will call your app. You can use any name you want here.

  2. What should the window title be?
    This will be the title of the default main window. You can use any title you want here.

  3. Where are your web assets (HTML/CSS/JS) located relative to the <current dir>/src-tauri/tauri.conf.json file that will be created?
    This is the path that Tauri will load your frontend assets from when building for production.

    Use ../ui for this value.

  4. What is the URL of your dev server?
    This can be either a URL or a file path that Tauri will load during development.

    Use ../ui for this value.

  5. What is your frontend dev command?
    This is the command used to start your frontend dev server.

    You can leave this blank since nothing needs to be compiled.

  6. What is your frontend build command?
    This is the command to build your frontend files.

    You can leave this blank since nothing needs to be compiled.

    3.Invoke Commands

    Tauri lets you enhance your frontend with native capabilities. We call these Commands, essentially Rust functions that you can call from your frontend JavaScript. This enables you to handle heavy processing or calls to the OS in much more performant Rust code.

    Let's make a simple example:

    src-tauri/src/main.rs

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

    A Command is just like any regular Rust function, with the addition of the #[tauri::command] attribute macro that allows your function to communicate with the JavaScript context.

    Lastly, we also need to tell Tauri about our newly created command so that it can route calls accordingly. This is done with the combination of the .invoke_handler() function and the generate_handler![] macro you can see below:

    src-tauri/src/main.rs

    fn main() {
      tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
    }
    

    Now you're ready to call your Command from the frontend!

    We would normally be recommending the @tauri-apps/api package here, but since we're not using a bundler for this guide, please enable withGlobalTauri in your tauri.conf.json file:

    tauri.conf.json

    {
      "build": {
        "beforeBuildCommand": "",
        "beforeDevCommand": "",
        "devPath": "../ui",
        "distDir": "../ui",
        "withGlobalTauri": true
      },
    

    This will inject a pre-bundled version of the API functions into your frontend.

    You can now modify your index.html file to call your Command:

    index.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <h1 id="header">Welcome from Tauri!</h1>
        <script>
          // access the pre-bundled global API functions
          const { invoke } = window.__TAURI__.tauri
    
          // now we can call our Command!
          // You will see "Welcome from Tauri" replaced
          // by "Hello, World!"!
          invoke('greet', { name: 'World' })
            // `invoke` returns a Promise
            .then((response) => {
              window.header.innerHTML = response
            })
        </script>
      </body>
    </html>

    5.App Publishing

    1. Build Your Web App

    Now that you are ready to package your project, you need to run your framework's or bundler's build command (assuming you're using one, of course).

    NOTE

    Every framework has its publishing tooling. It is outside of the scope of this document to treat them all or keep them up to date.

    2. Bundle your application with Tauri

    npm run tauri build
    

    This command embeds your web assets into a single binary with your Rust code. The binary itself will be located in src-tauri/target/release/[app name], and installers will be located in src-tauri/target/release/bundle/.

    Like the tauri dev command, the first time you run this, it takes some time to collect the Rust crates and build everything - but on subsequent runs, it only needs to rebuild your app's code, which is much quicker.

    Referce:

    1.Tauri:跨平台探索之旅-51CTO.COM

    2.Quick Start | Tauri Apps


Profile picture of MikeHe-creator

Written By

Who-am-I?

No bio found