1667984165
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.
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:
// 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
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.
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.
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.
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).
cat /etc/debian_version
or
dpkg --print-architecture
or
uname -m
or
arch
detect 386, amd64, arm, or arm64 OS architecture via terminal
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 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.
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.
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.
pnpm - choose your UI template
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 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
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
The default Tauri folder structure comes with pnpm create tauri-app
:
Tauri default folder structure
next.config.js
file for Next.js configuration.next-env.d.ts
file automatically generates for TypeScriptpackage.json
file contains all information for npm, yarn, and pnpm.pnpm-lock.yaml
file is created by pnpm to store all package information with the version.README.MD
file contains all the information about the project.src
folder contains all the Next.js code with pages, components, and CSS files.src-tauri
folder for Rust and Rust configuration.src-tauri/icons
contains all icons for the app.src-tauri/Cargo.lock
generated by cargo to store all package information.src-tauri/Cargo.toml
generated by cargo and store all packages and confirmation for the project.src-tauri/src
used to write the Rust code.src-tauri/target
generated by the pnpm tauri dev
command. It contains all the binary for the project.tauri.config.json
file used for Tauri configuration. 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.
The icon is important for the application. The user will click on the icon to open your application in Windows, macOS, and Linux.
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 tauriGenerating 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
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
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.
Run tauri build command
After successfully running the tauri build
command, Tauri generates two files:
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.
.deb
file extension is used for Debian..AppImage
file extension is used for all Linux distros to install the app..dmg
file extension is used for macOS..msi
file extension is used for Windows..snap
file extension is used for the Linux distro..deb
and .AppImage
locallyTo 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
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
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):
package.json
fileFirstly 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
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
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
You'll get an error while validating snapcraft.yaml
with the pnpm tauri-snap
command.
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 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 ubuntu
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
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
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.
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.
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
To solve this error, you need to run the snap command with the --dangerous
flag.
Install snap locally package
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.
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.
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 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 : devel
in
In the devel
mode, you'll see a message on the application installation page. devel
means 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.
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.
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.
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.
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.
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
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
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.
Click this link
After that, a new page is opened in the browser:
Submit pull request in AppImage
Create a pull request into appimage.github.io
7. Add the comment and click the create pull request button.
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
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.
You can build an application cross-architecture (cross-compilation) with Rust. Rust Toolchain helps you build cross-compilation applications.
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
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.
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.
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
1663318032
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.
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:
Tauri currently supports development and distribution on the following platforms:
Platform | Versions |
---|---|
Windows | 7 and above |
macOS | 10.15 and above |
Linux | See 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):
libwebkit2gtk-4.0-37
, libgtk-3-0
, libayatana-appindicator3-1
1webkit2gtk
, gtk3
, libayatana-appindicator
1webkit2gtk3
, gtk3
, libappindicator-gtk3
11 appindicator
is only required if system trays are used
Detail | Tauri | Electron |
---|---|---|
Installer Size Linux | 3.1 MB | 52.1 MB |
Memory Consumption Linux | 180 MB | 462 MB |
Launch Time Linux | 0.39s | 0.80s |
Interface Service Provider | WRY | Chromium |
Backend Binding | Rust | Node.js (ECMAScript) |
Underlying Engine | Rust | V8 (C/C++) |
FLOSS | Yes | No |
Multithreading | Yes | Yes |
Bytecode Delivery | Yes | No |
Multiple Windows | Yes | Yes |
Auto Updater | Yes | Yes1 |
Custom App Icon | Yes | Yes |
Windows Binary | Yes | Yes |
macOS Binary | Yes | Yes |
Linux Binary | Yes | Yes |
iOS Binary | Soon | No |
Android Binary | Soon | No |
Desktop Tray | Yes | Yes |
Sidecar Binaries | Yes | No |
Tauri is a system composed of a number of moving pieces:
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.
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 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
Test all the things! We have a number of test suites, but are always looking to improve our coverage:
cargo test
) => sourced via inline #[cfg(test)]
declarationsjest
) => via spec filesWe recommend you read this article to understand better how we run our pipelines: https://www.jacobbolda.com/setting-up-ci-and-cd-for-tauri/
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 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
1661432280
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.
WIP
WIP
WIP
WIP
Author: Layendan
Source code: https://github.com/Layendan/NineAnimator-Tauri
#svelte #javascript #typescript #rust #tauri
1661417520
A sleek music player app for your local library
Features:
This app is built using Svelte + Tauri.
Author: basharovV
Source code: https://github.com/basharovV/musicat
#svelte #javascript #typescript #tauri
1657751760
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-sass
Solidテンプレートを選択します。
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/
1657749600
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!
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.
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 .
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-sass
modelo Solid.
cd
na 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.
Nosso aplicativo, que chamei /Your-Tauri-App
de , 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
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 fetch
para fazer uma solicitação para uma rota, usaremos invoke
para 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_handler
método no construtor Tauri.
Então, usando o invoke
método, chamamos esse comando de Solid. Vamos atualizar nosso App.js
arquivo:
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 invoke
e 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.
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.json
para o que você quiser.
Para mim, após a conclusão da compilação, havia AppImage
e Deb
arquivos disponíveis em src-tauri/target/bundle
.
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:
Boa codificação!
Fonte: https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/
1657747920
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 后端绑定,因为用户决定实现它们。
与 Electron 一样,Tauri 使用多进程方法。Core 进程本质上是应用程序的后端,所有数据模型和应用程序逻辑都是用 Rust 编写的。WebView 进程是在您选择的 JavaScript 框架中构建的应用程序 UI。你甚至可以使用非 JavaScript 选项,例如使用 Dominator 或 ClojureScript 的 Rust。
这两个进程通过事件或命令(即 RPC 调用)进行通信。当另一个进程执行特定操作时,任何一个进程都可以发出另一个进程可以监听的事件以触发一个进程中的逻辑。
WebView 进程可以发出命令来触发核心进程中的预定义功能。这些是必不可少的RPC 调用。
要安装所有内容,我建议遵循官方文档中的本指南。你需要安装 Node.js 和 Rust。一切都设置好后,您可以通过运行以下命令来创建应用程序:
npx create-tauri-app
您将获得用于 WebView 的框架或语言的多个选项。对于本教程,选择SolidJS,然后选择ts-sass
Solid 模板。
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/
1657746000
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!
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.
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 .
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-sass
plantilla Solid.
cd
en 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.
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
Puede pensar en comandos como escribir sus rutas en el backend de una aplicación web estándar. Sin embargo, en lugar de usar fetch
para hacer una solicitud a una ruta, usaremos invoke
para 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_handler
método en el constructor Tauri.
Luego, usando el invoke
método, llamamos a este comando desde Solid. Actualicemos nuestro App.js
archivo:
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 invoke
y 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.
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.json
lo que desee.
AppImage
Para mí, después de completar la compilación , había Deb
archivos disponibles en formato src-tauri/target/bundle
.
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:
¡Feliz codificación!
Fuente: https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/
1657744020
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à 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.
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 .
Để 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-sass
mẫu Solid.
cd
và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.
Ứ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
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_handler
phương thức trong trình tạo Tauri.
Sau đó, sử dụng invoke
phương thức này, chúng tôi gọi lệnh này từ Solid. Hãy cập nhật App.js
tệ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 invoke
và 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.
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.json
bất kỳ thứ gì bạn muốn.
Đối với tôi, sau khi xây dựng hoàn thành, có AppImage
và Deb
các tệp có sẵn trong src-tauri/target/bundle
.
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:
Chúc bạn viết mã vui vẻ!
Nguồn: https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/
1657742400
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!
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.
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 .
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-sass
modèle Solid.
cd
dans 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.
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
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 fetch
pour faire une demande à une route, nous utiliserons invoke
pour 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_handler
méthode dans le constructeur Tauri.
Ensuite, en utilisant la invoke
méthode, nous appelons cette commande depuis Solid. Mettons à jour notre App.js
fichier :
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 invoke
et 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.
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.json
que vous voulez.
Pour moi, une fois la construction terminée, il y avait AppImage
et Deb
des fichiers disponibles dans src-tauri/target/bundle
.
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 :
Bon codage !
Source : https://blog.logrocket.com/rust-solid-js-tauri-desktop-app/
1657719480
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/
1651892272
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.
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.
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:
Detail | Tauri | Electron |
---|---|---|
Installer Size Linux | 3.1 MB | 52.1 MB |
Memory Consumption Linux | 180 MB | 462 MB |
Launch Time Linux | 0.39s | 0.80s |
Interface Service Provider | WRY | Chromium |
Backend Binding | Rust | Node.js (ECMAScript) |
Underlying Engine | Rust | V8 (C/C++) |
FLOSS | Yes | No |
Multithreading | Yes | Yes |
Bytecode Delivery | Yes | No |
Multiple Windows | Yes | Yes |
Auto Updater | Yes | Yes1 |
Custom App Icon | Yes | Yes |
Windows Binary | Yes | Yes |
MacOS Binary | Yes | Yes |
Linux Binary | Yes | Yes |
iOS Binary | Soon | No |
Android Binary | Soon | No |
Desktop Tray | Yes | Yes |
Sidecar Binaries | Yes | No |
Tauri is a system composed of a number of moving pieces:
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.
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 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
Test all the things! We have a number of test suites, but are always looking to improve our coverage:
cargo test
) => sourced via inline #[cfg(test)]
declarationsjest
) => via spec filesWe recommend you read this article to understand better how we run our pipelines: https://www.jacobbolda.com/setting-up-ci-and-cd-for-tauri/
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
1622532610
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
1594221893
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:
We will look at how to build a native cross-platform application from an existing web project. Let’s get to it!
Note: This article assumes you are comfortable with HTML, CSS, JavaScript, and Vue.js.
The official website sums up Tauri well:
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).
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:
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