Debbie Clay

Debbie Clay

1667984165

Build a Desktop-Based Cross-Platform App with with Next.js and Tauri

In this tutorial, you'll learn how to use Tauri and Next.js to build a desktop-based cross-platform application and publish it to the Snap store and AppImage.

Tauri is a new Rust-based framework that builds an x86_64 cross-platform application for Windows, macOS, and Linux.

So why is building a cross-platform app, that works on Windows, Mac, and Linux, important these days? Well, it helps companies target a larger audience and increase their revenue, without having to build three separate apps.

Many companies and developers use Next.js as a front-end when building a website. In this tutorial, we'll use Next and Tauri to build a desktop-based cross-platform application that'll be available on Windows, macOS, and Linux.

Demo of the project

To build this cross-platform application, you need Tauri, markdown, Contentlayer, pnpm, and Next.js. If you check how my application looks, you can install the application with snap-cli, AppImage, or download the application via the link and install it.

Let's see what these tools do:

  • we'll use Next.js for building the frontend part of the website
  • the markdown npm package helps convert markdown files into HTML
  • the Contentlayer npm package helps us manage markdown files in the project.
  • we'll use Tauri to build the cross-platform application binary
  • and finally, we'll use pnpm as our Node package manager.
// Install with snap
snap install static-blog-app

or

// install with AppImage
https://github.com/officialrajdeepsingh/static-blog-app/releases/download/v0.0.2/static-blog-app_0.0.2_amd64.AppImage

or

// Install on macOS
https://github.com/officialrajdeepsingh/static-blog-app/releases/download/v0.0.2/static-blog-app_0.0.2_x64.dmg

or

// Install on Windows
https://github.com/officialrajdeepsingh/static-blog-app/releases/download/v0.0.2/static-blog-app_0.0.2_x64_en-US.msi

Install static-blog-app in the different operating systems

Table of contents:

  • What is Next.js?
  • What is Tauri?
  • Computer Architecture
  • How to Create a New Project with Next.js and Tauri
  • How to Build an Application with Tauri
  • How to Build an Application for the Snap Store or Snapcraft
  • How to Build a Cross-Platform Application with GitHub Actions
  • How to Publish the App
  • FAQ
  • Conclusion

What is Next.js?

Next is a framework base on React. It has many features that let you build a website and enhance the user experience.

To learn more about Next, you can read this helpful tutorial I found on freeCodeCamp written by Reed Barger.

What is Tauri?

Tauri is a new framework that helps you build cross-platform desktop applications. Tauri is built based on the Rust language. Rust is faster, more secure, and has fewer memory issues than other languages.

Tauri has many features, but I'll mention some of the important ones for a front-end developer.

  1. Tauri supports HTML, CSS, and JavaScript.
  2. Tauri supports a lot of front-end frameworks and libraries, for example, React.js, Next.js, Vite, and Svelte kit.
  3. With Tauri, you don't need to learn GTK, GJS, and app build commands or AppImage builder.
  4. Tauri provides JavaScript API support. You can use it inside JS easily. For example, the window API helps all tasks related to the window.
  5. You can quickly build a cross-application bundler size with one command.
  6. Tauri provides an update handler to update older Tauri versions to the newest. You do not need to use other services and libraries to achieve the self-update functionality.
  7. In Tauri, you call Rust functions within JavaScript.

Tauri improves the development experience by providing an inbuilt JavaScript, npm, and Rust CLI tool, plugins, and the tauri-action GitHub workflow.

All these tools help you write code faster and create a production-ready app in less time. But the big thing Tauri provides is beginner-ready, easily understandable documentation.

GTK is a free and open-source cross-platform widget toolkit for creating graphical user interfaces for applications.

GJS is a JavaScript library for Gnome to build application interfaces. GJS is built on the SpiderMonkey JavaScript engine.

Computer Architecture

Every operating system comes with different architecture. Building cross-platform applications or performing cross-compilation is not easy. Based on the architecture, you can understand where the application is run. In other words, which architecture requires running our applications like i386, ARM, or x86_64?

The most common architectures in the computer science world are ARM, i386, and AMD (x86_64). Less technical users might know it as 64 or 32-bit architecture.

Rust uses different types of architecture to install itself. In my case, my laptop hardware support x86_64  and I have Ubuntu installed. On Ubuntu x86_64, the default stable-x86_64-unknown-linux-gnu Rust toolchain is used to build Tauri applications.

The Rust toolchain builds AMD (x86_64) applications. That is why Tauri builds cross-platform application (for Windows, macOs, and Linux distros) but does not build cross-architecture ones (builds applications for all ARM, i386, and x86_67 architecture).

How to check your architecture in Linux by command:

cat /etc/debian_version

	or 
    
dpkg --print-architecture

	or
    
uname -m

	or
    
arch

detect 386, amd64, arm, or arm64 OS architecture via terminal

How to check which toolchain Tauri is using:

The toolchain is a utility provided by Rust itself. You can install different toolchains with the rustup command.

You can use different types of Rust toolchains according to your computer's architecture. You can easily check which toolchain is installed in your operating system with the tauri npm, yarn, or pnpm command.

In my project, I'm using pnpm to create a new project, so I use the pnpm command. Again, based on the toolchain, we build apps for different architectures.

The default Ubuntu (x86_64) is based on the stable-x86_64-unknown-linux-gnu toolchain. The Rust stable-x86_64-unknown-linux-gnu toolchain builds only AMD-based applications.

The Rust toolchain is different according to the operating system and distro you're using. The default Rust toolchain is installed when you install Rust on your computer.

Here are the commands to check your architecture:

pnpm tauri info

or

yarn tauri info

or

npm run tauri info

Check that your architecture comes with Rust in your system by default.pnpm tauri info command outputpnpm tauri info command output

Tauri officially supports macOS, Windows, and Linux distros and you can't build mobile applications with Tauri (you'll face lots of issues, and after resolving them all you'll end up building your mobile app directly).

I found a great tutorial on the Rust toolchain as well as cross-compilation. The tutorial guides you and provides you with a deeper understanding of the Rust toolchain.

You can use the rustup command to install a different type of toolchain if you'd like. To learn more about the Rust toolchain and the rustup command, I'd suggest starting with the Rust toolchain docs.

How to Create a New Project with Next.js and Tauri

You can create a Tauri app with bash, cargo, PowerShell npm, yarn, or pnpm. We'll use pnpm to create a new Tauri set-up in this tutorial. pnpm is the new package manager for Node.js.

Create the UI template in Tauri

You can use different types of front-end frameworks for the Tauri app, for example, Vue, React, Svelte, Solid, Next.js, Preact, Angular, and Svelte. I've chosen to use Nextjs as the front-end template for our Tauri app in this tutorial.

Screenshot-from-2022-10-11-12-44-05

pnpm - choose your UI template

Create a new application with pnpm

You can use any other node package manager to create a new app like yarn or npm. I choose the pnpm node package manager, because pnpm is fast compared to yarn and npm.  

pnpm create tauri-app

set-up new tauri-app with pnpmcreate tauri-app with nextjsCreate tauri-app with nextjs

Now Tauri has created the my-demo app successfully. You can directly change the directory (folder) cd my-demo with the change directory (cd) command. Then you can run the pnpm install command to install all the dependencies required for the project. Finally, run the tauri dev command to lunch a new Tauri application window.

Run local development server in tauri

Run local development server in tauri

After downloading and compiling the code, you can see a new window open in your system using the pnpm tauri dev command.

Open a new window by tauri

Open a new window by tauri

The default Tauri folder structure comes with pnpm create tauri-app:

Tauri default folder structure

Tauri default folder structure

  1. You use the next.config.js file for Next.js configuration.
  2. The next-env.d.ts file automatically generates for TypeScript
  3. The package.json file contains all information for npm, yarn, and pnpm.
  4. The pnpm-lock.yaml file is created by pnpm to store all package information with the version.
  5. The README.MD file contains all the information about the project.
  6. The src folder contains all the Next.js code with pages, components, and CSS files.
  7. You use the src-tauri folder for Rust and Rust configuration.
  8. src-tauri/icons contains all icons for the app.
  9. src-tauri/Cargo.lock generated by cargo to store all package information.
  10. src-tauri/Cargo.toml generated by cargo and store all packages and confirmation for the project.
  11. src-tauri/src used to write the Rust code.
  12. src-tauri/target generated by the pnpm tauri dev command. It contains all the binary for the project.
  13. tauri.config.json file used for Tauri configuration.  

Create the UI for the app with Next.js

I'm using my old Next.js static site and I'll convert it into a desktop application. The Next static website code is available on GitHub so you can easily download it.

First, I need to copy my old posts along with the public, components, and pages folders and paste them into the new Tauri project. Then I'll remove the bootstrap CSS, and use Tailwind CSS to design the application's layout.

I already explained the process step-by-step on how to install TailwindCSS with Next in this article. You can read and follow the same setup to install Tailwind if you don't have it installed already.

Generate an icon for the application

The icon is important for the application. The user will click on the icon to open your application in Windows, macOS, and Linux.

Serach your application in ubuntu

Ubuntu static-blog-app icon

Generating icons for applications with various types and sizes can be complicated. You need icons for Windows, macOS, and Linux. Every operating system has its own guidelines for icons.

Tauri comes with a CLI tool that generates cross-operating system icons for applications based on icon configuration in Tauri. Here's the command to generate the icons:

pnpm tauri icon path-of-image

Genrating icons for tauricreate-icon-for-appGenerating icons

You can use an online website to generate icons for Tauri, and then add all icons into the tauri-app/src-tauri/icons folder.

You can change the icon configuration in the tauri-app/src-tauri/tauri.conf.json file:

"icon": [
        "icons/32x32.png",
        "icons/128x128.png",
        "icons/128x128@2x.png",
        "icons/icon.icns",
        "icons/icon.ico"
],

default icons configuration comes with tauri

How to Build an Application with Tauri

To build the application in Tauri, you need to run only one command in the terminal. Tauri automatically generates the build applications.

The first application is for the .deb Debian-based distro and the second application is appImage. The application build file changes from operating system to operating system.

AppImage is a universal application distribution for the cross-Linux distro. So you create one AppImage and run your application on any distro.

pnpm tauri build

Build tauri app

The first time you run the tauri build command, you may face a bundle identifier error in the terminal.

_bundle-identifier-error-in-tauri

Bundle identifier error

To solve the bundle identifier error, first open the my-demo/src-tauri/tauri.conf.json file and find identifier. Then change the "identifier": "com.tauri.dev" value according to your app. Make sure the identifier value is unique across the application.

"identifier": "com.officialrajdeepsingh.blog",

change Identifier value

After changing the identifier in the tauri.conf.json file, rerun the pnpm tauri build command.

tauri-building-application

Run tauri build command 

After successfully running the tauri build command, Tauri generates two files:

  1. my-demo_0.0.0_amd64.deb
  2. my-demo_0.0.0_amd64.AppImage

The bot file binary works only for the amd64 architecture and doesn't work on the arm and i386 architecture.

The file extension tells us where we use it.

  1. .deb file extension is used for Debian.
  2. .AppImage file extension is used for all Linux distros to install the app.
  3. .dmg file extension is used for macOS.
  4. .msi file extension is used for Windows.
  5. .snap file extension is used for the Linux distro.

Install .deb and .AppImage locally

To test for both binary  my-demo_0.0.0_amd64.deb and my-demo_0.0.0_amd64.AppImage, first install them locally and check that everything is working fine.

.deb file

❯ dpkg -i static-blog-app_0.0.2_amd64

.AppImage file

Firstly add the file permission for executing and then run the file.

Step 1: run chmod +x my-demo_0.0.0_amd64.AppImage

Step 2: run ./my-demo_0.0.0_amd64.AppImage hit enter to run AppImage base binary.

Tauri automatically generates both .deb and .AppImage files with their own file names.

Both files use the same naming conversion syntax all around the world. This file name conversion is not for Tauri. The Flatpak builder and Snapcraft also use the same kind of file naming syntax.

Syntax

<name-of-appliciation> <version> <architecture> <File extension>

Example
1. my-demo_0.0.0_amd64.deb
2. my-demo_0.0.0_amd64.AppImage

Syntax

How to Build an Application for the Snap Store or Snapcraft

Snapcraft or the Snap store is a Linux application distribution. It helps distribute your applications across Linux distros. Users can install your application with one click and the use of a command line (Terminal).

Snapcraft is maintained and built by Canonical (Ubuntu). Canonical provides all Linux application distributions and does not work for macOS and Windows.

Before building a snap, first you need to install Snapcraft.

sudo apt-get update
sudo snap install snapcraft --classic

Install snapcraft

How to build an application for the Snap store

I will guide you with a simple way to generate the snap file for Snapcraft. The snap file is a binary file, similar to the .deb  file. The Snap store uses a special .snap extension for the file. That indicates that it's a snap application installed on a linux distro.

You can also develop your first snap app quickly if you are a beginner – simply follow these steps (we'll go through each one by one):

  1. Install the tauri-snap-packager npm package
  2. Add configuration in the package.json file
  3. Build the snap
  4. Handle any errors
  5. How to fix the tauri-snap-packager takes too much time error

Install tauri-snap-packager npm package

Firstly install the tauri-snap-packager npm package in your project. The tauri-snap-packager npm package helps you create a snapcraft configuration file.

npm install --save-dev tauri-snap-packager

# Or with yarn

yarn add --dev tauri-snap-packager

# Or with pnpm

pnpm add tauri-snap-packager

install npm package

Add configuration in the package.json file

After installation, complete the tauri-snap-package npm package. Now configure the  "tauri-snap": "tauri-snap-packager" tauri-snap-package script in the package.json file.

"scripts": {
    "dev": "next dev -p 1420",
    "build": "next build && next export -o dist",
    "tauri": "tauri",
    "lint": "next lint",
    
    "tauri-snap": "tauri-snap-packager"
    
  },

config the script in package.json

Build the snap

Now you run the pnpm tauri-snap command in your project folder. tauri-snap automatically creates a snap folder in src-tauri/target. Inside the snap folder pnpm tauri-snap creates a new snapcraft.yaml file with all the configurations. All the configuration is based on your Tauri configuration.

name: static-blog-app
base: core18
version: 0.0.2
summary: Tauri app.
description: Awesome Tauri app.
grade: devel
confinement: strict
source-code: https://github.com/officialrajdeepsingh/static-blog-app
apps:
  static-blog-app:
    command: static-blog-app
    extensions:
      - gnome-3-34
    desktop: static-blog-app.desktop
parts:
  dump-binary:
    plugin: dump
    source: ./target/release
    source-type: local
    stage:
      - lib
      - icons
      - static-blog-app
      - static-blog-app.desktop
    prime:
      - lib
      - icons
      - static-blog-app
      - static-blog-app.desktop
    stage-packages:
      - libc6

Create a file src-tauri/target/snap/snapcraft.yaml

How to fix the errors

You'll get an error while validating snapcraft.yaml with the pnpm tauri-snap command.

Issues while validating snapcraft.yaml

Issues while validating snapcraft.yaml

Your application name may contain some words that are not allowed, like spaces, numbers, uppercase letters, and so on. For example, Static-blog-website does not allow you to use your name with a capital letter. Simply use a small case word for a name like static-blog-website.

You might also see an error you need 'multipass' set-up to build snaps when running the pnpm tauri-snap --trace-warnings command.

The --trace-warnings Node.js flag helps debug or trace the error.

You need 'multipass' set-up to build snaps

You need a multipass set-up to build snaps error.

To solve the error, you must install the multipass package in Ubuntu. The tauri-snap-package uses the Snapcraft command as a background to build a snap file. So Snapcraft requires multipass to build a snap package.

sudo snap install multipass

Install multipassInstall multipass in ubuntuInstall multipass in ubuntu

Tauri-snap-packager takes too much time.

If the tauri-snap-packager takes too much time to build the snap binary or you feel your application is stuck and does not show any output in the terminal, then just stop the command. The tauri-snap-packager isn't working for you, so you can use the snapcraft command.

Create a snap configuration with Tauri-snap-packager

Create a snap configuration with Tauri-snap-packager 

This error means that the pnpm tauri-snap the command is not working and it takes too much time. It's likely because the tauri-snap-package npm package isn't working correctly.

To solve this issue, run the snapcraft command in the same folder where your snap folder was created. Before running the snapcraft command, first, install the snapd command tool. Snapd is a REST API daemon for managing snap packages. To learn more about snapd, I found a great article written by Oyetoke Tobi Emmanuel.

snap install --channel stable snapd

Install snapd (Optional)

After installation is complete, run the snapcraft command in the tauri-app/src-tauri/target folder. The target folder is generated by the pnpm tauri dev command.

Face common error with snapcraft command.

Face common error with snapcraft command 

You may get a snap "core18" has no updates available error with Snapcraft. But the core18 is not a big issue. Simply update your distro package with the sudo apt-get update && sudo apt-get upgrade command, then restart your terminal or laptop. Here's a youtube tutorial that can help you solve your core18 error problem.

"Snapd has not logged" means that first, you need to login into your snapcraft account. For login run snapcraft login.

After you solve the core 18 issue, now run the snapcraft command again and build your snap binary file.

Build a new binary with snapcraft

Create a binary with snapcraft

The Snapcraft creates a new binary static-blog-app_0.0.0_amd64.snap file. Now the static-blog-app_0.0.0_amd64.snap file is ready to publish on the Snapcraft website or snap store.

How to install static-blog-app_0.0.0_amd64.snap locally in the system

If you install the static-blog-app_0.0.0_amd64.snap file locally with the following command, you might find the signatures metadata error.

sudo snap install ./static-blog-app_0.0.0_amd64.snap

install local snap 

Here's the error:

cannot find signatures metadata error for snap

cannot find signatures metadata error for snap

To solve this error, you need to run the snap command with the --dangerous flag.

Install snap locally package

Install snap locally package

How to Build a Cross-Platform Application with GitHub Actions

GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform or pipeline that allows you to automate tasks like building, testing, and deployment.

You can triage GitHub actions on certain events like somebody pushing new code to the GitHub repository and running tests on the code. If the test passes then the code gets added to the main or master branch.

If you want to build cross-platform applications for Windows, macOS, and Linux, the easiest way is using the GitHub actions workflow. This workflow runs on a specific event like push, pull, and so on.

To try this out, you'll need to create a new action in your project. First, create a new .github/workflows folder. After in the workflows, create a file with any name with a .yml extension.

The Tauri app provides a GitHub action configuration. With Tauri actions, you can quickly build cross-platform applications for Windows, macOS, and Linux distros with the GitHub workflow.

name: Build application
on:
  push:
    branches:
      - 'main'
  workflow_dispatch:

jobs:
  release:
    strategy:
      fail-fast: false
      matrix:
        platform: [macos-latest, ubuntu-latest, windows-latest]
    runs-on: ${{ matrix.platform }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Install Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 16

      - uses: pnpm/action-setup@v2.0.1
        name: Install pnpm
        id: pnpm-install
        with:
          version: 7.13.1
          run_install: false

      - name: Get pnpm store directory
        id: pnpm-cache
        run: |
          echo "::set-output name=pnpm_cache_dir::$(pnpm store path)"

      - uses: actions/cache@v3
        name: Setup pnpm cache
        with:
          path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-

      - name: Rust setup
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable

      - name: Install dependencies (ubuntu only)
        if: matrix.platform == 'ubuntu-latest'
        run: |
          sudo apt-get update
          sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
      - name: Install app dependencies and build web
        run: yarn && yarn build

      - name: Build the app
        uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.STATIC_BLOG_APP }}
        with:
          tagName: v__VERSION__ # tauri-action replaces \_\_VERSION\_\_ with the app version
          releaseName: 'v__VERSION__'
          releaseBody: 'See the assets to download this version and install.'
          releaseDraft: true
          prerelease: false

create an action in a my-demo/.github/workflows/build.yml folder.

Following the GitHub action, you can build your application on every push after successfully building the application and show all files in the GitHub release assets section.

Show all applications in the assets section

Show all applications in the assets section.

How to Publish the App

Publishing the package is the core of this article. A lot of people build their own Linux applications. But then they can't figure out how to submit the app on various distributions like Snapcraft, AppImage, and Homebrew.

So now I'll show how to submit a static-blog-app to Snapcraft and AppImage.

How to publish the app into the snap store or snapcraft

To publish a new package on the snap store, make sure you have a .snap binary available. Otherwise, first, build the .snap binary for the application (which we already went over above).

Go to the target or whatever folder where you created the .snp binary. Then run the snapcraft command. Make sure you first log in with your Snapcraft account. For login, run snapcraft login. Then run the following command with the argument I mentioned:

Syntax:

snapcraft upload <Opation> name-of-file

Publish a new package to snapPublish a new package to snapcraftPublish a new package to snap in devel release

After successfully getting into your account, then you can add or change the information regarding your package icon, name, and so on.

snapcraft upload --release=stable ./static-blog-app_0.0.0_amd64.snap

--release tag is not working because we add grade : develin 

In the devel mode, you'll see a message on the application installation page. devel means development mode.

Application in development mode

Application in development mode

By default, your package publishes all the information collected by src-tauri/target/snap/snapcraft.yaml in the edge release. To understand more about the Snapcraft release system, you can read the release documentation.

staticblogappforlinux

Go to the dashboard and add or update all the information regarding the app.

Make sure to use a banner image with a size of 720 x 240 for the snap.

How to publish your application on Snapcraft

When you upload your application to your Snapcraft account, your application is private. To change how it's published, drag your available release into one of the release channels.

Go to the dashboard> my snap> select your snap> releases, and according to your requirements, add your application to one of the provided releases. The default is edge release.

releases-in-snap

How to add an application to a stable release

To change the application to a stable release, go to the snap configuration src-tauri/target/snap/snapcraft.yaml file and update your  grade: devel to grade: stable:

....

grade: stable

....

Only change grade:devel to grade: stable in snapcraft.yaml

Now your application goes to stable release or channel and re-uploads your application.

Publish a snap image in stable release

The application automatically goes to a stable release if you do not mention- release tags.

Now you've successfully released your application in a stable release.

How to update your snap application

For updating the snap application, you need to make changes in the tauri/target/snap/snapcraft.yaml file in the version section.

...

version: 0.0.1

or 
version: 1.0.0

or

version: 0.1.0

...

Simple change the version value according to you

Now rebuild your application with the snapcraft command.

Rebuild your application

Rebuild your application

After successfully building your application, re-upload your latest build, and your application will be updated on the snap store website.

Update your application in snapcraft

Update your application in snapcraft

How to publish applications in AppImage

AppImage helps you distribute your application across Linux distros. You don't need to install AppImage for it to work in your system.

Publishing the application on AppImage is a straightforward process. First, you need an AppImage URL and a GitHub account.

First, go to the appImage GitHub repository and click on this link.  

Submit application into appimage

Click this link

After that, a new page is opened in the browser:

Submit pull request in appimage

Submit pull request in AppImage

  1. Add your application name.
  2. Paste your image URL
  3. Add comment
  4. Click the new propose file button.
  5. Download the appimage.github.io repo in your GitHub account
  6. Create a new pull request into the appimage.github.io repository.

Create a pull request into appimage.github.io

Create a pull request into appimage.github.io

7. Add the comment and click the create pull request button.

Create a pull request into appimage.github.io

Add comment and Create a pull request into appimage.github.io

Now your application is successfully submitted to the appimage.github.io repository. The appimage.github.io runs GitHub actions based on your application. Your application should pass all tests run AppImage. After that, your image should be successfully listed on AppImage so everybody can download your application.

If you submit an application on AppImage with a pull request, your GitHub action test will fail. You'll see the GLIBC_2.29' not found error.

I tried many ways to solve this issue, but I couldn't find a solution. If I do, I'll update my repository as well as this article.

GLIBC_2.29 is not found in ubuntu

GLIBC_2.29 is not found

FAQ

If you're building the application with Tauri, do you have to code in Rust?

No, you can build an application without writing a single line of code in Rust. Instead, Tauri provides JavaScript and TypeScript API support for front-end development to handle a lot of stuff like clipboard, dialog, event, HTTP, notification, and so on.

How do you build cross-platform architecture (cross-compilation) with Tauri?

You can build an application cross-architecture (cross-compilation) with Rust. Rust Toolchain helps you build cross-compilation applications.

What is the toolchain in Tauri?

The Rust toolchain helps you build an application on a different architecture. In rust, there are 86 toolchains available for a different architectures.

❯ rustup target list

check the available toolchain in rust

Can you use Tauri to build an Android or IOS application?

No, you can't use Tauri to build applications for Android and iOS. But there is a library that helps you build applications for mobile phones – I just haven't tested it yet. You can build applications with a toolchain. I'll soon write an article about this on my website.

What are Tauri JavaScript and TypeScript API?

Tauri provides a different type of API that helps enhance the user and developer experience. You can use the API to handle notifications, dialog, events, HTTP, and so on.

Conclusion

It's relatively easy to build cross-platform applications with Tauri. You can use any front-end framework for the application.

But other frameworks don't let you build various cross-architecture and cross-operating system applications, for example, Windows, macOS, and Linux distros.

Tauri comes with strong backend language support. With Rust, you can do anything you can with a low-level language. In addition, Rust provides memory safety, no garbage collector, and so on.

When building the Tauri application with Flatpak, I couldn't find a development and distribution solution. However, in the future, I will add it to the GitHub readme file.

I haven't covered how to distribute applications on Windows and macOS. I'm a Linux user and do not test applications on Windows and macOS. But there are lots of articles and videos on the internet you can check out to learn how to do that.

MacOS has a popular distribution platform called homebrew. The homebrew distribution system is similar to appimage.org. If you submit a new pull request for your application and pass all tests, your app shows on homebrew.

If you have any questions or suggestions related to developing and distributing a Tauri application, you can ask for help on the Tauri GitHub discussions.

Original article source at https://www.freecodecamp.org

#nextjs #tauri #linux #rust

Build a Desktop-Based Cross-Platform App with with Next.js and Tauri
Daisy Rees

Daisy Rees

1663318032

Tauri: Desktop Apps on Windows, MacOS, Linux with JavaScript & Rust

Tauri is a tool for building cross-platform desktop apps on Windows, MacOS, and Linux with JavaScript & Rust. It is very lightweight and fast compared to similar tools like Electron. 

Introduction

Tauri is 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.

The user interface in Tauri apps currently leverages tao as a window handling library on macOS and Windows, and gtk on Linux via the Tauri-team incubated and maintained WRY, which creates a unified interface to the system webview (and other goodies like Menu and Taskbar), leveraging WebKit on macOS, WebView2 on Windows and WebKitGTK on Linux.

Get Started

If you are interested in making a tauri app, please visit the documentation website. This README is directed towards those who are interested in contributing to the core library. But if you just want a quick overview about where tauri is at in its development, here's a quick burndown:

Platforms

Tauri currently supports development and distribution on the following platforms:

PlatformVersions
Windows7 and above
macOS10.15 and above
LinuxSee below
iOS/iPadOS (coming soon) 
Android (coming soon) 

Linux Support

For developing Tauri apps refer to the Getting Started guide on tauri.app.

For running Tauri apps we support the below configurations (these are automatically added as dependencies for .deb and are bundled for AppImage so that your users don't need to manually install them):

  • Debian (Ubuntu 18.04 and above or equivalent) with the following packages installed:
    • libwebkit2gtk-4.0-37, libgtk-3-0, libayatana-appindicator3-11
  • Arch with the following packages installed:
    • webkit2gtk, gtk3, libayatana-appindicator1
  • Fedora (latest 2 versions) with the following packages installed:
    • webkit2gtk3, gtk3, libappindicator-gtk31

1 appindicator is only required if system trays are used

App Bundles

  •  App Icons
  •  Build on macOS (.app, .dmg)
  •  Build on Linux (.deb, AppImage)
  •  Build on Windows (.exe, .msi)
  •  Copy Buffer
  •  Device Notifications (toast)
  •  Self Updater
  •  App Signing
  •  Frameless Mode
  •  Transparent Mode
  •  Multiwindow Mode
  •  Tray
  •  deeplink RPC (in progress)
  •  One-Time commands (coming soon)

Security Features

  •  localhost-free (:fire:)
  •  custom protocol for secure mode
  •  Dynamic ahead of Time Compilation (dAoT) with functional tree-shaking
  •  functional Address Space Layout Randomization
  •  OTP salting of function names and messages at runtime
  •  CSP Injection

Utilities

  •  GH Action for creating binaries for all platforms
  •  VS Code Extension
  •  Tauri Core Plugins
  •  Update core dependencies automatically from the command line
  •  Rust-based CLI

Comparison between Tauri and Electron

DetailTauriElectron
Installer Size Linux3.1 MB52.1 MB
Memory Consumption Linux180 MB462 MB
Launch Time Linux0.39s0.80s
Interface Service ProviderWRYChromium
Backend BindingRustNode.js (ECMAScript)
Underlying EngineRustV8 (C/C++)
FLOSSYesNo
MultithreadingYesYes
Bytecode DeliveryYesNo
Multiple WindowsYesYes
Auto UpdaterYesYes1
Custom App IconYesYes
Windows BinaryYesYes
macOS BinaryYesYes
Linux BinaryYesYes
iOS BinarySoonNo
Android BinarySoonNo
Desktop TrayYesYes
Sidecar BinariesYesNo

Notes

  1. Electron has no native auto updater on Linux, but is offered by electron-packager

Development

Tauri is a system composed of a number of moving pieces:

Infrastructure

  • Git for code management
  • GitHub for project management
  • GitHub actions for CI and CD
  • Discord for discussions
  • Netlify-hosted documentation website
  • DigitalOcean Meilisearch instance

Major Runtimes

  • Node.js for running the CLI (deno and pure rust are on the roadmap)
  • Cargo for testing, running the dev service, building binaries and as the runtime harness for the webview

Major Languages

  • Rust for the CLI
  • ECMAScript bindings to the Rust API, written in typescript
  • Rust for bindings, rust side of the API, harnesses
  • Rust plugins to Tauri backend

Operating systems

Tauri core can be developed on Mac, Linux and Windows, but you are encouraged to use the latest possible operating systems and build tools for your OS.

Contributing

Before you start working on something, it's best to check if there is an existing issue first. It's also a good idea to stop by the Discord server and confirm with the team if it makes sense or if someone else is already working on it.

Please make sure to read the Contributing Guide before making a pull request.

Thank you to everyone contributing to Tauri!

Documentation

Documentation in a polyglot system is a tricky proposition. To this end, we prefer to use inline documentation of Rust code and at JSDoc in typescript / javascript code. We autocollect these and publish them using Docusaurus v2 and netlify. Here is the hosting repository for the documentation site: https://github.com/tauri-apps/tauri-docs

Testing & Linting

Test all the things! We have a number of test suites, but are always looking to improve our coverage:

  • Rust (cargo test) => sourced via inline #[cfg(test)] declarations
  • TS (jest) => via spec files
  • Smoke Tests (run on merges to latest)
  • eslint, clippy

CI/CD

We recommend you read this article to understand better how we run our pipelines: https://www.jacobbolda.com/setting-up-ci-and-cd-for-tauri/

Organization

Tauri aims to be a sustainable collective based on principles that guide sustainable free and open software communities. To this end it has become a Programme within the Commons Conservancy, and you can contribute financially via Open Collective.

Semver

tauri is following Semantic Versioning 2.0.

Download Details: 
Author: tauri-apps
Source Code: https://github.com/tauri-apps/tauri 
License: Apache-2.0, MIT licenses found
#tauri #javascript #rust 

Tauri: Desktop Apps on Windows, MacOS, Linux with JavaScript & Rust
Joseph  Murray

Joseph Murray

1661432280

Nine Animator: Anime Viewing App for Desktop Built with Svelte & Tauri

A simple yet elegant way of waching anime on your favorite anime websites. NineAnimataur(i) is a free and open source anime watching app for Desktop, using Sveltekit and Tauri.

Table of Contents

  • NineAnimataur(i)
    • Table of Contents
    • Features
    • Picture in Picture Playback
    • Notifications & Subscription
    • Download Episodes
    • Google Cast
    • Screenshots
      • Dark Appearance
      • Light Appearance
    • License

Features

  •  Ads Free and no logins
  •  Super-duper clean UIs + Dark Mode
  •  Get notifications when new episodes come out
  •  Custom video playback interface
  •  Picture in Picture playback
  •  Chromecast/Google Cast integration
  •  Playback History & Auto Resumes
  •  Support Custom Sources
  •  Discord Rich Presence integration
  •  Download & play episodes offline
  •  Third party anime
  •  Custom anime lists, e.g. favorites and to-watch list

Picture in Picture Playback

WIP

Notifications & Subscription

WIP

Download Episodes

WIP

Google Cast

WIP

Screenshots

Dark Appearance

Light Appearance

 

Download details:

Author: Layendan
Source code: https://github.com/Layendan/NineAnimator-Tauri

#svelte #javascript #typescript #rust #tauri

Nine Animator: Anime Viewing App for Desktop Built with Svelte & Tauri
Joseph  Murray

Joseph Murray

1661417520

Building A Sleek Music Player App for Local Lib using Stelve & Tauri

Musicat

A sleek music player app for your local library 

Features:

  • Import
    •  Supports MP3, FLAC, AAC, OGG, WAV
    •  Basic info from ID3 tags (title, artist, album, genre, year)
    •  Advanced metadata from ID3 tags
    •  Recursive folder import
    •  Import via song/folder drag and drop
  • Library
    •  Basic table with sorting by indexed fields
    •  Delete track
    •  Delete in bulk
    •  Look up tracks on YouTube / Wikipedia via right click
    •  Look up chords and lyrics on DuckDuckGo
    •  Basic search (matching by 'starts with' on title, album or artist)
    •  Advanced search
  • Player
    •  Current track info and artwork
    •  Show format, bitrate, sample rate
    •  Seekbar
    •  EQ visualizer
    •  Media keys support (also Space for play/pause)
    •  Shuffle

This app is built using Svelte + Tauri.

Demo

screenshot

Download details:

Author: basharovV
Source code: https://github.com/basharovV/musicat

#svelte #javascript #typescript #tauri 

Building A Sleek Music Player App for Local Lib using Stelve & Tauri
坂本  篤司

坂本 篤司

1657751760

Rust、SolidJS、Tauri:クロスプラットフォームのデスクトップアプリを作成する

2022年12月15日、GitHubはATOM IDEの日と呼びます。これは、最初の実際のElectronアプリケーションとしてソフトウェアの歴史の中で特別な位置を占めています。

Electronを使用すると、開発者は、Windows、Mac、およびLinux用のクロスプラットフォームデスクトップアプリケーションを構築するために、すでに使い慣れている標準のWebテクノロジを使用できます。これはすべて、Atom、VSCode、Postmanなどのアプリケーションに最適ですが、常に理想的であるとは限りません。たとえば、Electronアプリに対する一般的な批判の1つは、C、C ++、Rust、Goなどの低レベル言語が使用するものに比べて多くのメモリを消費することが多いということです。

この記事では、ほとんどの主要なデスクトッププラットフォーム用のバイナリを構築するための新しいフレームワークであるTauriについて説明します。始めましょう! 

タウロイとは?

Tauriは、Electronについて人々が最も気に入っているものを提供するが、セキュリティとパフォーマンスの問題の多くを修正する新しいフレームワークです。Tauriは、HTML、CSS、JavaScriptなどのWebテクノロジーを使用してUIを設計する機能を提供しますが、低レベルの言語を使用してアプリケーションとバックエンドロジックを記述できます。

執筆時点では、Tauriは主にバックエンド言語としてRustをサポートしていますが、そのAPIは複数の言語に実装できます。時間の経過とともに、ユーザーが実装を決定すると、C、C ++、Go、Ruby、Python、さらにはJavaScriptバックエンドバインディングが期待できます。

タウロイのアーキテクチャの概要

Electronと同様に、Tauriはマルチプロセスアプローチを使用しています。コアプロセスは基本的に、Rustで記述されたすべてのデータモデルとアプリケーションロジックを備えたアプリケーションのバックエンドです。WebViewプロセスは、選択したJavaScriptフレームワークに組み込まれているアプリケーションUIです。DominatorやClojureScriptを使用したRustなどのJavaScript以外のオプションを使用することもできます。

2つのプロセスは、RPC呼び出しであるイベントまたはコマンドのいずれかを介して通信します。どちらのプロセスも、他のプロセスが特定のアクションを実行したときに、他のプロセスがリッスンして1つのプロセスのロジックをトリガーできるイベントを発行できます。

WebViewプロセスは、コアプロセスで事前定義された関数をトリガーするコマンドを発行できます。これらは必須のRPC呼び出しです。

タウロイを試乗

すべてをインストールするには、公式ドキュメントのこのガイドに従うことをお勧めします。Node.jsとRustがインストールされている必要があります。すべての設定が完了したら、次のコマンドを実行してアプリを作成できます。

npx create-tauri-app

WebViewに使用するフレームワークまたは言語のいくつかのオプションが提供されます。このチュートリアルでは、SolidJSを選択してから、ts-sassSolidテンプレートを選択します。

 

cd新しいフォルダに移動して、を実行しますnpm install。次に、を実行しますnpm run tauri dev。これにより、CoreプロセスとWebViewプロセスがオンになり、でプレビューできるようになりますlocalhost:3000。このページには、基本的に1秒ごとにカウントされている数値が表示されます。

アプリを正常にビルドするためにインストールする必要のあるライブラリや環境変数がある可能性があるため、端末の出力に注意してください。私はPOPOSで作業しており、すべての依存関係を設定する前に、いくつかのライブラリをインストールする必要がありました。

フォルダ構造

私が呼び出したアプリは/Your-Tauri-App、次のフォルダー構造を使用します。

/Your-Tauri-App
|
|-- /node_modules //All the NPM Libraries
|
|-- /src // Your frontend UI Code for the WebView Process
|
|-- /src-tauri // Your backend code for the Core process in Rust
|
|-- .gitignore // files to be ignored by git
|-- index.html // just the HTML file the WebView mounts to
|-- package-lock.json // lockfile for npm
|-- package.json // config file for npm
|-- pnpm-lock.yaml // lock file for pnpm
|-- readme.md // template readme
|-- tsconfig.json // Typescript Configurations
|-- vite.config.js // Vite configurations

基本的なコマンドの作成

標準のWebアプリケーションのバックエンドでルートを作成するようなコマンドを考えることができます。fetchただし、を使用してルートにリクエストを送信する代わりにinvoke、フロントエンドからこれらのコマンドの1つを呼び出すために使用します。

で非常に基本的なコマンドを作成しましょう/src-tauri/src/main.rs

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


// Our Tauri Command
#[tauri::command]
fn return_string(word: String) -> String{
    return word
}

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

マクロは関数をコマンドに変換し、Tauriビルダー#[tauri::command]のメソッドを使用してコマンドをアプリに登録します。invoke_handler

次に、invokeメソッドを使用して、Solidからこのコマンドを呼び出します。App.jsファイルを更新しましょう:

import { invoke } from '@tauri-apps/api/tauri';
import { Component, createSignal } from 'solid-js';
import './App.scss';
import Counter from './Counter';

const App: Component = () => {
  const [counter, setCounter] = createSignal(0);
  setInterval(setCounter, 1000, (c: number) => c + 1);

  async function handleClick(event){

    // Invoke the command from our backend using the invoke function
    const result = await invoke("return_string", {
      word: "This is the argument"
    })

    // print the result to an alert
    alert(result)
  }

  return (
    <>
      <div>
        <h1 class="header">{counter()}</h1>
        <button onClick={handleClick}>Click Me</button>
      </div>
      <Counter />
    </>
  );
};

export default App;

上記のコードでは、invokeメソッドをインポートしimport { invoke } from '@tauri-apps/api/tauri';ます。invoke呼び出すコマンドの名前を持つ文字列と、名前による任意の引数を持つオブジェクトの2つの引数を呼び出して渡します。

これで、新しいClick Me ボタンをクリックすると、送信したテキストが返送され、バックエンドからメソッドが正常に呼び出されたことを確認できます。それでおしまい!Rustおよび任意のRustライブラリを使用してコマンドを作成し、アプリケーションのデータ管理のニーズを処理できます。

アプリケーションの構築

執筆時点では、Tauriはクロスコンパイルをサポートしていないため、現在使用しているオペレーティングシステム(私の場合はLinux)にコンパイルされます。

これを有効にするには、を実行するだけですnpm run tauri build。の識別子プロパティを必要なものに更新しtauri.config.jsonてください。

私の場合、ビルドが完了した後、にファイルがありましAppImageた。Debsrc-tauri/target/bundle

結論

Tauriは、Webテクノロジーとお気に入りのフロントエンドフレームワークを使用してデスクトップアプリを開き、パフォーマンスを向上させ、バンドルを小さくします。Tauriは確かに、多くのElectron開発者を、パフォーマンスの向上が必要なアプリに切り替えるように誘惑するでしょう。

Tauriの機能のほんの一部にすぎませんが、次の優れた機能を確認することをお勧めします。

  • イベントでコードをトリガーする
  • ウィンドウメニューの作成
  • ウィンドウのカスタマイズ

ハッピーコーディング! 

ソース:https ://blog.logrocket.com/rust-solid-js-tauri-desktop-app/

#rust #solidity #tauri 

Rust、SolidJS、Tauri:クロスプラットフォームのデスクトップアプリを作成する

Rust, SolidJS E Tauri: Crie Um Aplicativo De Desktop Multiplataforma

Em 15 de dezembro de 2022, o GitHub encerrará o dia para o ATOM IDE , que ocupa um lugar especial na história do software como o primeiro aplicativo real do Electron.

A Electron permitiu que os desenvolvedores usassem tecnologias padrão da Web com as quais já estavam familiarizados para criar aplicativos de desktop multiplataforma para Windows, Mac e Linux. Tudo isso é ótimo para aplicativos como Atom, VSCode e Postman, mas nem sempre é o ideal. Por exemplo, uma crítica comum aos aplicativos Electron é que eles costumam usar muita memória em relação ao que uma linguagem de nível inferior, como C, C++, Rust ou Go usaria.

Neste artigo, exploraremos o Tauri , uma nova estrutura para criar binários para a maioria das principais plataformas de desktop. Vamos começar! 

O que é Tauri?

Tauri é uma nova estrutura que oferece o que as pessoas mais gostam no Electron, mas corrige muitas das preocupações de segurança e desempenho. O Tauri oferece a capacidade de projetar sua interface do usuário usando tecnologias da Web como HTML, CSS e JavaScript, mas permite que você use linguagens de nível inferior para escrever o aplicativo e a lógica de back-end.

No momento da escrita, Tauri suporta principalmente Rust como a linguagem de back-end, mas sua API pode ser implementada em vários idiomas. Com o tempo, podemos esperar ligações de back-end C, C++, Go, Ruby, Python e até JavaScript conforme os usuários decidem implementá-las.

Resumo da arquitetura de Tauri

Assim como o Electron, o Tauri usa uma abordagem multiprocesso. O processo Core é essencialmente o backend do aplicativo com todos os modelos de dados e lógica do aplicativo escritos em Rust. O processo WebView é a interface do usuário do aplicativo que é construída na estrutura JavaScript de sua escolha. Você pode até usar opções não JavaScript como Rust usando Dominator ou ClojureScript.

Os dois processos se comunicam por meio de eventos ou comandos, que são chamadas RPC. Qualquer processo pode emitir eventos que o outro processo pode ouvir para acionar a lógica em um processo quando o outro processo executa uma ação específica.

O processo WebView pode emitir comandos para acionar funções predefinidas no processo principal. Estas são chamadas RPC essenciais .

Levando Tauri para um test drive

Para instalar tudo, recomendo seguir este guia dos documentos oficiais. Você precisará do Node.js e do Rust instalados. Depois que tudo estiver configurado, você poderá criar um aplicativo executando o seguinte comando:

npx create-tauri-app

Você terá várias opções de qual estrutura ou linguagem usar para o WebView. Para este tutorial, selecione SolidJS e, em seguida, o ts-sassmodelo Solid.

 

cdna nova pasta e execute npm install. Em seguida, execute npm run tauri dev, que ativa os processos Core e WebView para que você possa visualizá-lo em localhost:3000. A página basicamente exibe apenas um número que está contando a cada segundo.

Preste atenção à saída do terminal porque pode haver bibliotecas e variáveis ​​ambientais que você precisa instalar para que o aplicativo seja compilado com sucesso. Estou trabalhando em um sistema operacional POP e tive que instalar várias bibliotecas antes de ter todas as dependências.

A estrutura de pastas

Nosso aplicativo, que chamei /Your-Tauri-Appde , usará a seguinte estrutura de pastas:

/Your-Tauri-App
|
|-- /node_modules //All the NPM Libraries
|
|-- /src // Your frontend UI Code for the WebView Process
|
|-- /src-tauri // Your backend code for the Core process in Rust
|
|-- .gitignore // files to be ignored by git
|-- index.html // just the HTML file the WebView mounts to
|-- package-lock.json // lockfile for npm
|-- package.json // config file for npm
|-- pnpm-lock.yaml // lock file for pnpm
|-- readme.md // template readme
|-- tsconfig.json // Typescript Configurations
|-- vite.config.js // Vite configurations

Criando um comando básico

Você pode pensar em comandos como escrever suas rotas no back-end de um aplicativo da web padrão. No entanto, em vez de usar fetchpara fazer uma solicitação para uma rota, usaremos invokepara chamar um desses comandos do nosso frontend.

Vamos criar um comando bem básico em /src-tauri/src/main.rs:

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


// Our Tauri Command
#[tauri::command]
fn return_string(word: String) -> String{
    return word
}

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

A #[tauri::command]macro transforma nossa função em um comando, e registramos nosso comando no app com o invoke_handlermétodo no construtor Tauri.

Então, usando o invokemétodo, chamamos esse comando de Solid. Vamos atualizar nosso App.jsarquivo:

import { invoke } from '@tauri-apps/api/tauri';
import { Component, createSignal } from 'solid-js';
import './App.scss';
import Counter from './Counter';

const App: Component = () => {
  const [counter, setCounter] = createSignal(0);
  setInterval(setCounter, 1000, (c: number) => c + 1);

  async function handleClick(event){

    // Invoke the command from our backend using the invoke function
    const result = await invoke("return_string", {
      word: "This is the argument"
    })

    // print the result to an alert
    alert(result)
  }

  return (
    <>
      <div>
        <h1 class="header">{counter()}</h1>
        <button onClick={handleClick}>Click Me</button>
      </div>
      <Counter />
    </>
  );
};

export default App;

No código acima, importamos o método invoke import { invoke } from '@tauri-apps/api/tauri';. Chamamos invokee passamos dois argumentos, uma string com o nome do comando a ser invocado e um objeto com qualquer argumento por nome.

Agora, quando clicamos no Click Me botão novo, o texto que enviamos será enviado de volta, confirmando que invocamos com sucesso o método do nosso backend. É isso! Você pode criar comandos usando Rust, bem como qualquer biblioteca Rust, para lidar com as necessidades de gerenciamento de dados do seu aplicativo.

Construindo o aplicativo

No momento em que escrevo, o Tauri não suporta compilação cruzada, então ele compilará para qualquer sistema operacional em que você esteja atualmente, no meu caso, Linux.

Para habilitar isso, tudo o que você precisa fazer é executar npm run tauri build. Apenas certifique-se de atualizar a propriedade do identificador no tauri.config.jsonpara o que você quiser.

Para mim, após a conclusão da compilação, havia AppImagee Debarquivos disponíveis em src-tauri/target/bundle.

Conclusão

Tauri abre aplicativos de desktop usando tecnologias da web e sua estrutura de front-end favorita para melhor desempenho e pacotes menores. Tauri certamente estará tentando muitos desenvolvedores do Electron a mudar para aplicativos que precisam de desempenho aprimorado.

Embora tenhamos apenas arranhado a superfície do que o Tauri é capaz, recomendo ler os seguintes recursos interessantes:

  • Acionando código com eventos
  • Criando um menu de janela
  • Personalizando a janela

Boa codificação! 

Fonte: https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/

#rust #solidity #tauri 

Rust, SolidJS E Tauri: Crie Um Aplicativo De Desktop Multiplataforma
许 志强

许 志强

1657747920

Rust、SolidJS 和 Tauri:创建跨平台桌面应用程序

2022 年 12 月 15 日,GitHub 将迎来 ATOM IDE 的一天,它作为第一个真正的 Electron 应用程序在软件历史上占有特殊的地位。

Electron 允许开发人员使用他们已经熟悉的标准 Web 技术来构建适用于 Windows、Mac 和 Linux 的跨平台桌面应用程序。这对于 Atom、VSCode 和 Postman 等应用程序来说都很棒,但并不总是理想的。例如,对 Electron 应用程序的一个常见批评是,与 C、C++、Rust 或 Go 等低级语言使用的内存相比,它们通常会占用大量内存。

在本文中,我们将探讨Tauri,这是一个为大多数主要桌面平台构建二进制文件的新框架。让我们开始吧! 

金牛座是什么?

Tauri是一个新框架,它提供了人们最喜欢 Electron 的东西,但解决了许多安全和性能问题。Tauri 提供了使用 HTML、CSS 和 JavaScript 等 Web 技术设计 UI 的能力,但允许您使用较低级别的语言来编写应用程序和后端逻辑。

在撰写本文时,Tauri 主要支持 Rust 作为后端语言,但它的 API 可以跨多种语言实现。随着时间的推移,我们可以期待 C、C++、Go、Ruby、Python 甚至 JavaScript 后端绑定,因为用户决定实现它们。

Tauri 的架构总结

与 Electron 一样,Tauri 使用多进程方法。Core 进程本质上是应用程序的后端,所有数据模型和应用程序逻辑都是用 Rust 编写的。WebView 进程是在您选择的 JavaScript 框架中构建的应用程序 UI。你甚至可以使用非 JavaScript 选项,例如使用 Dominator 或 ClojureScript 的 Rust。

这两个进程通过事件或命令(即 RPC 调用)进行通信。当另一个进程执行特定操作时,任何一个进程都可以发出另一个进程可以监听的事件以触发一个进程中的逻辑。

WebView 进程可以发出命令来触发核心进程中的预定义功能。这些是必不可少的RPC 调用

带着 Tauri 去试驾

要安装所有内容,我建议遵循官方文档中的本指南。你需要安装 Node.js 和 Rust。一切都设置好后,您可以通过运行以下命令来创建应用程序:

npx create-tauri-app

您将获得用于 WebView 的框架或语言的多个选项。对于本教程,选择SolidJS,然后选择ts-sassSolid 模板。

 

cd进入新文件夹并运行npm install. 然后,运行npm run tauri dev,这将打开 Core 和 WebView 进程,以便您可以在localhost:3000. 该页面基本上只显示一个每秒计数的数字。

注意终端输出,因为可能需要安装库和环境变量才能使应用程序成功构建。我正在使用 POP 操作系统,在它拥有所有依赖项之前,我必须安装几个库。

文件夹结构

我们的应用程序,我称之为/Your-Tauri-App,将使用以下文件夹结构:

/Your-Tauri-App
|
|-- /node_modules //All the NPM Libraries
|
|-- /src // Your frontend UI Code for the WebView Process
|
|-- /src-tauri // Your backend code for the Core process in Rust
|
|-- .gitignore // files to be ignored by git
|-- index.html // just the HTML file the WebView mounts to
|-- package-lock.json // lockfile for npm
|-- package.json // config file for npm
|-- pnpm-lock.yaml // lock file for pnpm
|-- readme.md // template readme
|-- tsconfig.json // Typescript Configurations
|-- vite.config.js // Vite configurations

创建基本命令

您可以考虑在标准 Web 应用程序的后端编写路由等命令。但是,我们将使用从我们的前端调用这些命令之一,而不是使用fetch向路由发出请求。invoke

让我们创建一个非常基本的命令/src-tauri/src/main.rs

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


// Our Tauri Command
#[tauri::command]
fn return_string(word: String) -> String{
    return word
}

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

宏将我们的函数转换为命令,然后我们使用Tauri 构建器中#[tauri::command]的方法将命令注册到应用程序中。invoke_handler

然后,使用该invoke方法,我们从 Solid 调用此命令。让我们更新我们的App.js文件:

import { invoke } from '@tauri-apps/api/tauri';
import { Component, createSignal } from 'solid-js';
import './App.scss';
import Counter from './Counter';

const App: Component = () => {
  const [counter, setCounter] = createSignal(0);
  setInterval(setCounter, 1000, (c: number) => c + 1);

  async function handleClick(event){

    // Invoke the command from our backend using the invoke function
    const result = await invoke("return_string", {
      word: "This is the argument"
    })

    // print the result to an alert
    alert(result)
  }

  return (
    <>
      <div>
        <h1 class="header">{counter()}</h1>
        <button onClick={handleClick}>Click Me</button>
      </div>
      <Counter />
    </>
  );
};

export default App;

在上面的代码中,我们导入了调用方法import { invoke } from '@tauri-apps/api/tauri';。我们调用invoke并传递两个参数,一个带有要调用的命令名称的字符串和一个带有名称的任何参数的对象。

现在,当我们单击新Click Me 按钮时,我们发送的文本将被发回,确认我们成功地从后端调用了该方法。而已!您可以使用 Rust 以及任何 Rust 库创建命令来处理应用程序的数据管理需求。

构建应用程序

在撰写本文时,Tauri 不支持交叉编译,因此它可以编译到您当前使用的任何操作系统,在我的例子中是 Linux。

要启用此功能,您所要做的就是运行npm run tauri build。只需确保将 中的标识符属性更新为tauri.config.json您想要的任何内容。

AppImage对我来说,Deb构建完成后,有src-tauri/target/bundle.

结论

Tauri 使用 Web 技术和您最喜欢的前端框架打开桌面应用程序,以获得更好的性能和更小的捆绑包。Tauri 肯定会吸引许多 Electron 开发人员转向需要提高性能的应用程序。

尽管我们只是了解了 Tauri 的功能,但我建议您阅读以下很酷的功能:

  • 使用事件触发代码
  • 创建窗口菜单
  • 自定义窗口

快乐编码! 

来源:https ://blog.logrocket.com/rust-solid-js-tauri-desktop-app/

#rust #solidity #tauri 

Rust、SolidJS 和 Tauri:创建跨平台桌面应用程序

Rust, SolidJS Y Tauri: Cree Una Aplicación De Escritorio Multiplatafor

El 15 de diciembre de 2022, GitHub dará por finalizado el IDE de ATOM , que ocupa un lugar especial en la historia del software como la primera aplicación real de Electron.

Electron permitió a los desarrolladores utilizar tecnologías web estándar con las que ya estaban familiarizados para crear aplicaciones de escritorio multiplataforma para Windows, Mac y Linux. Todo esto es excelente para aplicaciones como Atom, VSCode y Postman, pero no siempre es ideal. Por ejemplo, una crítica común de las aplicaciones de Electron es que a menudo usan mucha memoria en relación con lo que usaría un lenguaje de nivel inferior, como C, C ++, Rust o Go.

En este artículo, exploraremos Tauri , un nuevo marco para crear archivos binarios para la mayoría de las principales plataformas de escritorio. ¡Empecemos! 

¿Qué es Tauri?

Tauri es un nuevo marco que ofrece lo que más le gusta a la gente de Electron, pero soluciona muchos de los problemas de seguridad y rendimiento. Tauri ofrece la capacidad de diseñar su interfaz de usuario utilizando tecnologías web como HTML, CSS y JavaScript, pero le permite usar lenguajes de nivel inferior para escribir la aplicación y la lógica de back-end.

En el momento de escribir este artículo, Tauri admite principalmente Rust como lenguaje de back-end, pero su API se puede implementar en varios idiomas. Con el tiempo, podemos esperar enlaces de back-end de C, C++, Go, Ruby, Python e incluso JavaScript a medida que los usuarios decidan implementarlos.

Resumen de la arquitectura de Tauri

Al igual que Electron, Tauri utiliza un enfoque de procesos múltiples. El proceso Core es esencialmente el backend de la aplicación con todos los modelos de datos y la lógica de la aplicación escritos en Rust. El proceso de WebView es la interfaz de usuario de la aplicación que se crea en el marco de JavaScript de su elección. Incluso puede usar opciones que no sean de JavaScript como Rust usando Dominator o ClojureScript.

Los dos procesos se comunican a través de eventos o comandos, que son llamadas RPC. Cualquiera de los procesos puede emitir eventos que el otro proceso puede escuchar para activar la lógica en un proceso cuando el otro proceso realiza una acción particular.

El proceso WebView puede emitir comandos para activar funciones predefinidas en el proceso principal. Estas son llamadas RPC esenciales .

Tomando a Tauri para una prueba de manejo

Para instalar todo, recomiendo seguir esta guía de los documentos oficiales. Necesitará Node.js y Rust instalados. Una vez que todo esté configurado, puede crear una aplicación ejecutando el siguiente comando:

npx create-tauri-app

Se le darán varias opciones de qué marco o idioma usar para WebView. Para este tutorial, seleccione SolidJS y luego la ts-sassplantilla Solid.

 

cden la nueva carpeta y ejecutar npm install. Luego, ejecute npm run tauri dev, que activa los procesos Core y WebView para que pueda obtener una vista previa en localhost:3000. La página esencialmente solo muestra un número que cuenta cada segundo.

Preste atención a la salida del terminal porque puede haber bibliotecas y variables ambientales que necesita instalar para que la aplicación se compile correctamente. Estoy trabajando desde un sistema operativo POP y tuve que instalar varias bibliotecas antes de que tuviera todas las dependencias.

La estructura de carpetas

Nuestra aplicación, a la que he llamado /Your-Tauri-App, utilizará la siguiente estructura de carpetas:

/Your-Tauri-App
|
|-- /node_modules //All the NPM Libraries
|
|-- /src // Your frontend UI Code for the WebView Process
|
|-- /src-tauri // Your backend code for the Core process in Rust
|
|-- .gitignore // files to be ignored by git
|-- index.html // just the HTML file the WebView mounts to
|-- package-lock.json // lockfile for npm
|-- package.json // config file for npm
|-- pnpm-lock.yaml // lock file for pnpm
|-- readme.md // template readme
|-- tsconfig.json // Typescript Configurations
|-- vite.config.js // Vite configurations

Crear un comando básico

Puede pensar en comandos como escribir sus rutas en el backend de una aplicación web estándar. Sin embargo, en lugar de usar fetchpara hacer una solicitud a una ruta, usaremos invokepara llamar a uno de estos comandos desde nuestra interfaz.

Vamos a crear un comando muy básico en /src-tauri/src/main.rs:

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


// Our Tauri Command
#[tauri::command]
fn return_string(word: String) -> String{
    return word
}

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

La #[tauri::command]macro convierte nuestra función en un comando y registramos nuestro comando con la aplicación con el invoke_handlermétodo en el constructor Tauri.

Luego, usando el invokemétodo, llamamos a este comando desde Solid. Actualicemos nuestro App.jsarchivo:

import { invoke } from '@tauri-apps/api/tauri';
import { Component, createSignal } from 'solid-js';
import './App.scss';
import Counter from './Counter';

const App: Component = () => {
  const [counter, setCounter] = createSignal(0);
  setInterval(setCounter, 1000, (c: number) => c + 1);

  async function handleClick(event){

    // Invoke the command from our backend using the invoke function
    const result = await invoke("return_string", {
      word: "This is the argument"
    })

    // print the result to an alert
    alert(result)
  }

  return (
    <>
      <div>
        <h1 class="header">{counter()}</h1>
        <button onClick={handleClick}>Click Me</button>
      </div>
      <Counter />
    </>
  );
};

export default App;

En el código anterior, importamos el método de invocación import { invoke } from '@tauri-apps/api/tauri';. Lo llamamos invokey le pasamos dos argumentos, una cadena con el nombre del comando a invocar y un objeto con cualquier argumento por nombre.

Ahora, cuando hacemos clic en el Click Me botón nuevo, el texto que enviamos se devolverá, lo que confirma que invocamos con éxito el método desde nuestro backend. ¡Eso es todo! Puede crear comandos usando Rust, así como cualquier biblioteca de Rust para manejar las necesidades de administración de datos para su aplicación.

Construyendo la aplicación

Al momento de escribir, Tauri no admite la compilación cruzada, por lo que se compilará en cualquier sistema operativo en el que se encuentre actualmente, en mi caso, Linux.

Para habilitar esto, todo lo que tiene que hacer es ejecutar npm run tauri build. Solo asegúrese de actualizar la propiedad del identificador en tauri.config.jsonlo que desee.

AppImagePara mí, después de completar la compilación , había Debarchivos disponibles en formato src-tauri/target/bundle.

Conclusión

Tauri abre aplicaciones de escritorio que utilizan tecnologías web y su marco de interfaz de usuario favorito para un mejor rendimiento y paquetes más pequeños. Tauri sin duda tentará a muchos desarrolladores de Electron a hacer el cambio por aplicaciones que necesitan un rendimiento mejorado.

Aunque solo arañamos la superficie de lo que Tauri es capaz de hacer, recomiendo leer sobre las siguientes funciones interesantes:

  • Activación de código con eventos
  • Creación de un menú de ventana
  • Personalización de la ventana

¡Feliz codificación! 

Fuente: https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/ 

#rust #solidity #tauri 

Rust, SolidJS Y Tauri: Cree Una Aplicación De Escritorio Multiplatafor
Hoang  Ha

Hoang Ha

1657744020

Rust, SolidJS Và Tauri: Tạo Ứng Dụng Máy Tính để Bàn Đa Nền Tảng

Vào ngày 15 tháng 12 năm 2022, GitHub sẽ gọi đó là ngày dành cho ATOM IDE , nơi giữ một vị trí đặc biệt trong lịch sử phần mềm với tư cách là ứng dụng Electron thực sự đầu tiên.

Electron cho phép các nhà phát triển sử dụng các công nghệ web tiêu chuẩn mà họ đã quen thuộc để xây dựng các ứng dụng máy tính để bàn đa nền tảng cho Windows, Mac và Linux. Tất cả điều này đều tuyệt vời cho các ứng dụng như Atom, VSCode và Postman, nhưng nó không phải lúc nào cũng lý tưởng. Ví dụ, một lời chỉ trích phổ biến đối với các ứng dụng Electron là chúng thường sử dụng rất nhiều bộ nhớ so với ngôn ngữ cấp thấp hơn, như C, C ++, Rust hoặc Go sẽ sử dụng.

Trong bài viết này, chúng ta sẽ khám phá Tauri , một khuôn khổ mới để xây dựng các tệp nhị phân cho hầu hết các nền tảng máy tính để bàn chính. Bắt đầu nào! 

Tauri là gì?

Tauri là một khuôn khổ mới cung cấp những gì mọi người thích nhất về Electron nhưng khắc phục nhiều vấn đề về bảo mật và hiệu suất. Tauri cung cấp khả năng thiết kế giao diện người dùng của bạn bằng các công nghệ web như HTML, CSS và JavaScript nhưng cho phép bạn sử dụng các ngôn ngữ cấp thấp hơn để viết ứng dụng và logic phụ trợ.

Tại thời điểm viết bài, Tauri chủ yếu hỗ trợ Rust làm ngôn ngữ phụ trợ, nhưng API của nó có thể được triển khai trên nhiều ngôn ngữ. Theo thời gian, chúng ta có thể mong đợi các ràng buộc phụ trợ C, C ++, Go, Ruby, Python và thậm chí là JavaScript khi người dùng quyết định triển khai chúng.

Sơ lược về kiến ​​trúc của Tauri

Giống như Electron, Tauri sử dụng cách tiếp cận đa quy trình. Quy trình Core về cơ bản là phần phụ trợ của ứng dụng với tất cả các mô hình dữ liệu và logic ứng dụng được viết bằng Rust. Quy trình WebView là giao diện người dùng ứng dụng được xây dựng trong khung JavaScript mà bạn chọn. Bạn thậm chí có thể sử dụng các tùy chọn không phải JavaScript như Rust bằng Dominator hoặc ClojureScript.

Hai tiến trình giao tiếp thông qua các sự kiện hoặc lệnh, đó là các cuộc gọi RPC. Một trong hai quá trình có thể phát ra các sự kiện mà quá trình kia có thể lắng nghe để kích hoạt logic trong một quá trình khi quá trình kia thực hiện một hành động cụ thể.

Quy trình WebView có thể đưa ra các lệnh để kích hoạt các chức năng được xác định trước trong quy trình cốt lõi. Đây là những cuộc gọi RPC cần thiết .

Đưa Tauri lái thử

Để cài đặt mọi thứ, tôi khuyên bạn nên làm theo hướng dẫn này từ các tài liệu chính thức. Bạn sẽ cần cài đặt Node.js và Rust. Sau khi mọi thứ được thiết lập, bạn có thể tạo ứng dụng bằng cách chạy lệnh sau:

npx create-tauri-app

Bạn sẽ được cung cấp một số tùy chọn về khung hoặc ngôn ngữ để sử dụng cho WebView. Đối với hướng dẫn này, hãy chọn SolidJS và sau đó chọn ts-sassmẫu Solid.

 

cdvào thư mục mới và chạy npm install. Sau đó, chạy npm run tauri dev, bật quy trình Core và WebView để bạn có thể xem trước tại localhost:3000. Về cơ bản, trang này chỉ hiển thị một số đang đếm từng giây.

Hãy chú ý đến đầu ra của thiết bị đầu cuối vì có thể có các thư viện và biến môi trường bạn cần cài đặt để ứng dụng xây dựng thành công. Tôi đang làm việc từ HĐH POP và tôi đã phải cài đặt một số thư viện trước khi nó có tất cả các phụ thuộc.

Cấu trúc thư mục

Ứng dụng của chúng tôi, mà tôi đã gọi /Your-Tauri-App, sẽ sử dụng cấu trúc thư mục sau:

/Your-Tauri-App
|
|-- /node_modules //All the NPM Libraries
|
|-- /src // Your frontend UI Code for the WebView Process
|
|-- /src-tauri // Your backend code for the Core process in Rust
|
|-- .gitignore // files to be ignored by git
|-- index.html // just the HTML file the WebView mounts to
|-- package-lock.json // lockfile for npm
|-- package.json // config file for npm
|-- pnpm-lock.yaml // lock file for pnpm
|-- readme.md // template readme
|-- tsconfig.json // Typescript Configurations
|-- vite.config.js // Vite configurations

Tạo một lệnh cơ bản

Bạn có thể nghĩ về các lệnh như viết các tuyến đường của mình trong phần phụ trợ của một ứng dụng web tiêu chuẩn. Tuy nhiên, thay vì sử dụng fetchđể thực hiện một yêu cầu đối với một tuyến đường, chúng tôi sẽ sử dụng invokeđể gọi một trong những lệnh này từ giao diện người dùng của chúng tôi.

Hãy tạo một lệnh rất cơ bản trong /src-tauri/src/main.rs:

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


// Our Tauri Command
#[tauri::command]
fn return_string(word: String) -> String{
    return word
}

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

Macro biến hàm của #[tauri::command]chúng tôi thành một lệnh và chúng tôi đăng ký lệnh của mình với ứng dụng bằng invoke_handlerphương thức trong trình tạo Tauri.

Sau đó, sử dụng invokephương thức này, chúng tôi gọi lệnh này từ Solid. Hãy cập nhật App.jstệp của chúng tôi:

import { invoke } from '@tauri-apps/api/tauri';
import { Component, createSignal } from 'solid-js';
import './App.scss';
import Counter from './Counter';

const App: Component = () => {
  const [counter, setCounter] = createSignal(0);
  setInterval(setCounter, 1000, (c: number) => c + 1);

  async function handleClick(event){

    // Invoke the command from our backend using the invoke function
    const result = await invoke("return_string", {
      word: "This is the argument"
    })

    // print the result to an alert
    alert(result)
  }

  return (
    <>
      <div>
        <h1 class="header">{counter()}</h1>
        <button onClick={handleClick}>Click Me</button>
      </div>
      <Counter />
    </>
  );
};

export default App;

Trong đoạn mã trên, chúng tôi nhập phương thức gọi import { invoke } from '@tauri-apps/api/tauri';. Chúng tôi gọi invokevà chuyển cho nó hai đối số, một chuỗi với tên của lệnh để gọi và một đối tượng với bất kỳ đối số nào bằng tên.

Bây giờ, khi chúng tôi nhấp vào Click Me nút mới, văn bản chúng tôi đã gửi sẽ được gửi lại, xác nhận rằng chúng tôi đã gọi thành công phương thức từ chương trình phụ trợ của mình. Đó là nó! Bạn có thể tạo các lệnh bằng Rust cũng như bất kỳ thư viện Rust nào để xử lý các nhu cầu quản lý dữ liệu cho ứng dụng của mình.

Xây dựng ứng dụng

Tại thời điểm viết bài, Tauri không hỗ trợ biên dịch chéo, vì vậy nó sẽ biên dịch sang bất kỳ hệ điều hành nào bạn đang sử dụng, trong trường hợp của tôi là Linux.

Để kích hoạt điều này, tất cả những gì bạn phải làm là chạy npm run tauri build. Chỉ cần đảm bảo cập nhật thuộc tính mã định danh trong tauri.config.jsonbất kỳ thứ gì bạn muốn.

Đối với tôi, sau khi xây dựng hoàn thành, có AppImageDebcác tệp có sẵn trong src-tauri/target/bundle.

Sự kết luận

Tauri mở ra các ứng dụng dành cho máy tính để bàn sử dụng công nghệ web và khung giao diện người dùng yêu thích của bạn để có hiệu suất tốt hơn và các gói nhỏ hơn. Tauri chắc chắn sẽ thu hút nhiều nhà phát triển Electron thực hiện chuyển đổi cho các ứng dụng cần cải thiện hiệu suất.

Mặc dù chúng tôi mới chỉ sơ lược về khả năng của Tauri, nhưng tôi khuyên bạn nên đọc các tính năng thú vị sau:

  • Mã kích hoạt với các sự kiện
  • Tạo menu cửa sổ
  • Tùy chỉnh cửa sổ

Chúc bạn viết mã vui vẻ! 

Nguồn: https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/

#rust #solidity #tauri 

Rust, SolidJS Và Tauri: Tạo Ứng Dụng Máy Tính để Bàn Đa Nền Tảng
Léon  Peltier

Léon Peltier

1657742400

Rust, SolidJS Et Tauri : Créer Une Application De Bureau Multiplatefor

Le 15 décembre 2022, GitHub mettra un terme à l'IDE ATOM , qui occupe une place particulière dans l'histoire du logiciel en tant que première véritable application Electron.

Electron a permis aux développeurs d'utiliser des technologies Web standard qu'ils connaissaient déjà pour créer des applications de bureau multiplateformes pour Windows, Mac et Linux. Tout cela est idéal pour des applications comme Atom, VSCode et Postman, mais ce n'est pas toujours idéal. Par exemple, une critique courante des applications Electron est qu'elles utilisent souvent beaucoup de mémoire par rapport à ce qu'un langage de niveau inférieur, comme C, C++, Rust ou Go utiliserait.

Dans cet article, nous allons explorer Tauri , un nouveau framework permettant de créer des fichiers binaires pour la plupart des principales plates-formes de bureau. Commençons! 

Qu'est-ce que Tauri ?

Tauri est un nouveau cadre qui offre ce que les gens aiment le plus chez Electron, mais résout de nombreux problèmes de sécurité et de performances. Tauri offre la possibilité de concevoir votre interface utilisateur à l'aide de technologies Web telles que HTML, CSS et JavaScript, mais vous permet d'utiliser des langages de niveau inférieur pour écrire la logique de l'application et du backend.

Au moment de la rédaction de cet article, Tauri prend principalement en charge Rust comme langage principal, mais son API peut être implémentée dans plusieurs langages. Au fil du temps, nous pouvons nous attendre à des liaisons backend C, C++, Go, Ruby, Python et même JavaScript lorsque les utilisateurs décident de les implémenter.

Résumé de l'architecture de Tauri

Comme Electron, Tauri utilise une approche multi-processus. Le processus Core est essentiellement le backend de l'application avec tous les modèles de données et la logique d'application écrits en Rust. Le processus WebView est l'interface utilisateur de l'application qui est construite dans le framework JavaScript de votre choix. Vous pouvez même utiliser des options non-JavaScript comme Rust en utilisant Dominator ou ClojureScript.

Les deux processus communiquent via des événements ou des commandes, qui sont des appels RPC. L'un ou l'autre processus peut émettre des événements que l'autre processus peut écouter pour déclencher la logique dans un processus lorsque l'autre processus effectue une action particulière.

Le processus WebView peut émettre des commandes pour déclencher des fonctions prédéfinies dans le processus principal. Ce sont des appels RPC essentiels .

Prendre Tauri pour un essai routier

Pour tout installer, je vous recommande de suivre ce guide de la documentation officielle. Vous aurez besoin de Node.js et de Rust installés. Une fois que tout est configuré, vous pouvez créer une application en exécutant la commande suivante :

npx create-tauri-app

Vous aurez plusieurs options de framework ou de langage à utiliser pour WebView. Pour ce didacticiel, sélectionnez SolidJS , puis le ts-sassmodèle Solid.

 

cddans le nouveau dossier et exécutez npm install. Ensuite, exécutez npm run tauri dev, qui active les processus Core et WebView afin que vous puissiez le prévisualiser sur localhost:3000. La page affiche essentiellement un nombre qui compte chaque seconde.

Faites attention à la sortie du terminal car il peut y avoir des bibliothèques et des variables d'environnement que vous devez installer pour que l'application se construise avec succès. Je travaille à partir d'un système d'exploitation POP et j'ai dû installer plusieurs bibliothèques avant d'avoir toutes les dépendances.

La structure du dossier

Notre application, que j'ai appelée /Your-Tauri-App, utilisera la structure de dossiers suivante :

/Your-Tauri-App
|
|-- /node_modules //All the NPM Libraries
|
|-- /src // Your frontend UI Code for the WebView Process
|
|-- /src-tauri // Your backend code for the Core process in Rust
|
|-- .gitignore // files to be ignored by git
|-- index.html // just the HTML file the WebView mounts to
|-- package-lock.json // lockfile for npm
|-- package.json // config file for npm
|-- pnpm-lock.yaml // lock file for pnpm
|-- readme.md // template readme
|-- tsconfig.json // Typescript Configurations
|-- vite.config.js // Vite configurations

Création d'une commande de base

Vous pouvez penser à des commandes telles que l'écriture de vos itinéraires dans le backend d'une application Web standard. Cependant, au lieu d'utiliser fetchpour faire une demande à une route, nous utiliserons invokepour appeler l'une de ces commandes depuis notre interface.

Créons une commande très basique dans /src-tauri/src/main.rs:

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


// Our Tauri Command
#[tauri::command]
fn return_string(word: String) -> String{
    return word
}

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

La #[tauri::command]macro transforme notre fonction en une commande, et nous enregistrons notre commande avec l'application avec la invoke_handlerméthode dans le constructeur Tauri.

Ensuite, en utilisant la invokeméthode, nous appelons cette commande depuis Solid. Mettons à jour notre App.jsfichier :

import { invoke } from '@tauri-apps/api/tauri';
import { Component, createSignal } from 'solid-js';
import './App.scss';
import Counter from './Counter';

const App: Component = () => {
  const [counter, setCounter] = createSignal(0);
  setInterval(setCounter, 1000, (c: number) => c + 1);

  async function handleClick(event){

    // Invoke the command from our backend using the invoke function
    const result = await invoke("return_string", {
      word: "This is the argument"
    })

    // print the result to an alert
    alert(result)
  }

  return (
    <>
      <div>
        <h1 class="header">{counter()}</h1>
        <button onClick={handleClick}>Click Me</button>
      </div>
      <Counter />
    </>
  );
};

export default App;

Dans le code ci-dessus, nous importons la méthode ask import { invoke } from '@tauri-apps/api/tauri';. Nous appelons invokeet lui passons deux arguments, une chaîne avec le nom de la commande à invoquer et un objet avec n'importe quel argument par nom.

Maintenant, lorsque nous cliquons sur le nouveau Click Me bouton, le texte que nous avons envoyé sera renvoyé, confirmant que nous avons invoqué avec succès la méthode depuis notre backend. C'est ça! Vous pouvez créer des commandes à l'aide de Rust ainsi que de toutes les bibliothèques Rust pour gérer les besoins de gestion des données de votre application.

Construire l'application

Au moment d'écrire ces lignes, Tauri ne prend pas en charge la compilation croisée, il se compilera donc sur n'importe quel système d'exploitation sur lequel vous vous trouvez actuellement, dans mon cas, Linux.

Pour activer cela, tout ce que vous avez à faire est de lancer npm run tauri build. Assurez-vous simplement de mettre à jour la propriété d'identifiant dans ce tauri.config.jsonque vous voulez.

Pour moi, une fois la construction terminée, il y avait AppImageet Debdes fichiers disponibles dans src-tauri/target/bundle.

Conclusion

Tauri ouvre les applications de bureau à l'aide des technologies Web et de votre infrastructure frontale préférée pour de meilleures performances et des ensembles plus petits. Tauri incitera certainement de nombreux développeurs Electron à passer aux applications nécessitant des performances améliorées.

Bien que nous n'ayons fait qu'effleurer la surface de ce dont Tauri est capable, je vous recommande de lire les fonctionnalités intéressantes suivantes :

  • Code de déclenchement avec des événements
  • Création d'un menu de fenêtre
  • Personnalisation de la fenêtre

Bon codage ! 

Source : https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/

#rust #solidity #tauri 

Rust, SolidJS Et Tauri : Créer Une Application De Bureau Multiplatefor

Rust, SolidJS, and Tauri: Create a cross-platform desktop app

On December 15, 2022 GitHub will calling it a day for the ATOM IDE, which holds a special place in software history as the first real Electron application.

Electron allowed developers to use standard web technologies that they were already familiar with to build cross-platform desktop applications for Windows, Mac, and Linux. This is all great for applications like Atom, VSCode, and Postman, but it is not always ideal. For example, one common criticism of Electron apps is that they often use up a lot of memory relative to what a lower-level language, like C, C++, Rust, or Go would use.

In this article, we’ll explore Tauri, a new framework for building binaries for most major desktop platforms. Let’s get started!  

Source: https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/

#rust #solidity #tauri 

Rust, SolidJS, and Tauri: Create a cross-platform desktop app

Tauri: Build Smaller, Faster & Secure Desktop App with Web Frontend

Tauri in 100 Seconds

Tauri is a tool for building cross-platform desktop apps on Windows, MacOS, and Linux with JavaScript & Rust. It is very lightweight and fast compared to similar tools like Electron.  


Introduction

Tauri is 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.

The user interface in Tauri apps currently leverages tao as a window handling library on macOS and Windows, and gtk on Linux via the Tauri-team incubated and maintained WRY, which creates a unified interface to the system webview (and other goodies like Menu and Taskbar), leveraging WebKit on macOS, WebView2 on Windows and WebKitGTK on Linux.

To learn more about the details of how all of these pieces fit together, please consult this ARCHITECTURE.md document.

Get Started

If you are interested in making a tauri app, please visit the documentation website. This README is directed towards those who are interested in contributing to the core library. But if you just want a quick overview about where tauri is at in its development, here's a quick burndown:

Platforms

  • Windows 7,8,10
  • Linux
  • macOS
  • iOS (in progress)
  • android (soon)

App Bundles

  • App Icons
  • Build on MacOS (.app, .dmg)
  • Build on Linux (.deb, AppImage)
  • Build on Windows (.exe, .msi)
  • Copy Buffer
  • Device Notifications (toast)
  • Self Updater
  • App Signing
  • Frameless Mode
  • Transparent Mode
  • Multiwindow Mode
  • Tray
  • deeplink RPC (in progress)
  • One-Time commands (coming soon)

Security Features

  • localhost-free (:fire:)
  • custom protocol for secure mode
  • Dynamic ahead of Time Compilation (dAoT) with functional tree-shaking
  • functional Address Space Layout Randomization
  • OTP salting of function names and messages at runtime
  • CSP Injection

Utilities

  • GH Action for creating binaries for all platforms
  • VS Code Extension
  • Tauri Core Plugins
  • Update core dependencies automatically from the command line
  • Rust-based CLI

Comparison between Tauri and Electron

DetailTauriElectron
Installer Size Linux3.1 MB52.1 MB
Memory Consumption Linux180 MB462 MB
Launch Time Linux0.39s0.80s
Interface Service ProviderWRYChromium
Backend BindingRustNode.js (ECMAScript)
Underlying EngineRustV8 (C/C++)
FLOSSYesNo
MultithreadingYesYes
Bytecode DeliveryYesNo
Multiple WindowsYesYes
Auto UpdaterYesYes1
Custom App IconYesYes
Windows BinaryYesYes
MacOS BinaryYesYes
Linux BinaryYesYes
iOS BinarySoonNo
Android BinarySoonNo
Desktop TrayYesYes
Sidecar BinariesYesNo

Notes

  1. Electron has no native auto updater on Linux, but is offered by electron-packager

Development

Tauri is a system composed of a number of moving pieces:

Infrastructure

  • Git for code management
  • GitHub for project management
  • GitHub actions for CI and CD
  • Discord for discussions
  • Netlify-hosted documentation website
  • DigitalOcean meilisearch instance

Major Runtimes

  • Node.js for running the CLI (deno and pure rust are on the roadmap)
  • Cargo for testing, running the dev service, building binaries and as the runtime harness for the webview

Major Languages

  • Rust for the CLI
  • EcmaScript bindings to the Rust API, written in typescript
  • Rust for bindings, rust side of the API, harnesses
  • Rust plugins to Tauri backend

Operating systems

Tauri core can be developed on Mac, Linux and Windows, but you are encouraged to use the latest possible operating systems and build tools for your OS.

Contributing

Before you start working on something, it's best to check if there is an existing issue first. It's also is a good idea to stop by the Discord server and confirm with the team if it makes sense or if someone is already working on it.

Please make sure to read the Contributing Guide before making a pull request.

Thank you to everyone contributing to Tauri!

Documentation

Documentation in a polyglot system is a tricky proposition. To this end, we prefer to use inline documentation of Rust code and at JSDoc in typescript / javascript code. We autocollect these and publish them using Docusaurus v2 and netlify. Here is the hosting repository for the documentation site: https://github.com/tauri-apps/tauri-docs

Testing & Linting

Test all the things! We have a number of test suites, but are always looking to improve our coverage:

  • Rust (cargo test) => sourced via inline #[cfg(test)] declarations
  • TS (jest) => via spec files
  • Smoke Tests (run on merges to latest)
  • eslint, clippy

CI/CD

We recommend you read this article to understand better how we run our pipelines: https://www.jacobbolda.com/setting-up-ci-and-cd-for-tauri/

Organization

Tauri aims to be a sustainable collective based on principles that guide sustainable free and open software communities. To this end it has become a Programme within the Commons Conservancy, and you can contribute financially via Open Collective.

Tauri https://tauri.studio 
Tauri GitHub https://github.com/tauri-apps/tauri 

#tauri #programming 
 

Tauri: Build Smaller, Faster & Secure Desktop App with Web Frontend

Rahul Bhardwaj

1622532610

Learn How to Learn by reading Docs ft. Tauri

Today we will learn how we can learn something completely new by just reading docs and exploring the examples of a cross platform app development framework called Tauri which is an electron alternative which uses web-view and provides native system API to be used with JavaScript.

Tauri is a framework for building tiny, blazing 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.

Tauri website - Tauri.studio

Subscribe: https://www.youtube.com/c/CreativeJE/featured

#tauri #javascript

Learn How to Learn by reading Docs ft. Tauri
Oleta  Orn

Oleta Orn

1594221893

Creating Tiny Desktop Apps With Tauri And Vue.js

Tauri is a toolchain for creating small, fast, and secure desktop apps from your existing HTML, CSS, and JavaScript. In this article, Kelvin explains how Tauri plays well with the progressive framework Vue.js by integrating both technologies in bundling an example web app called nota as a native application.

Technology makes our lives better, not just users, but also creators (developers and designers). In this article, I’ll introduce you to Tauri. This article will be useful to you if:

  • you have been building applications on the web with HTML, CSS, and JavaScript, and you want to use the same technologies to create apps targeted at Windows, macOS, or Linux platforms;
  • you are already building cross-platform desktop apps with technologies like Electron, and you want to check out alternatives;
  • you want to build apps with web technologies for Linux distributions, such as PureOS;
  • you are a Rust enthusiast, and you’d like to apply it to build native cross-platform applications.

We will look at how to build a native cross-platform application from an existing web project. Let’s get to it!

NoteThis article assumes you are comfortable with HTML, CSS, JavaScript, and Vue.js.

WHAT IS TAURI?

The official website sums up Tauri well:

  • Tauri is a polyglot toolchain for building more secure native apps with both tiny and fast binaries. By “polyglot”, I mean that Tauri uses multiple programming languages. At the moment, Rust, JavaScript, and TypeScript are used. But there are plans to let you use Go, C++, Python, and more.
  • It lets you use any HTML and JavaScript-based front-end framework, such as Vue.js, React, or Angular, to build a native desktop app, and it can be integrated into any pipeline.
  • It helps you build and bundle binaries for major desktop platforms (mobile and WebAssembly coming soon).

So, basically, Tauri allows you to use web technologies to create tiny and secure native desktop apps.

On its GitHub page, Tauri is described as a framework-agnostic toolchain for building highly secure native apps that have tiny binaries (i.e. file size) and that are very fast (i.e. minimal RAM usage).

Why Not Electron?

A popular tool for using web technologies to build desktop applications is Electron.

However, Electron apps have a rather large bundle size, and they tend to take up a lot of memory when running. Here is how Tauri compares to Electron:

  • Bundle
  • The size of a Tauri app can be less than 600 KB.
  • Memory
  • The footprint of a Tauri app is less than half the size of an Electron app.
  • Licence
  • Relicensing is possible with Tauri, but not with Electron. Electron ships with Chromium right out of the box. However, Chromium includes a digital rights-management system named Widevine. The inclusion of Widevine in Chromium makes apps created with Electron frowned upon by users of platforms such as PureOS for the sole reason that it is not free/libre open-source software (FLOSS). Platforms like PureOS are verified by the Free Software Foundation (FSF). This means that they can only publish free and open-source software in their app stores.

In a nutshell, if your app is built with Electron, it will never be shipped officially in the PureOS store. This should be a concern for developers targeting such distributions.

#vue #vue.js #tauri #programming

Creating Tiny Desktop Apps With Tauri And Vue.js