Tauri
The plugin owns the catalog. The frontend gets whole chunks over the i18n-next:// protocol and resolves keys
itself with @i18n-micro: there is no IPC call per key. Install: Quick start.
Rust side
use tauri_plugin_i18n_next::ManagerExt;
macro_rules! file {
($path:literal) => { ($path, &include_bytes!(concat!("../../locales/", $path))[..]) };
}
let i18n = i18n_next::I18n::builder()
.config_json(include_str!("../../i18n.json"))
.files([file!("en.json"), file!("ru.json"), file!("pages/tray/en.json"), file!("pages/tray/ru.json")])
.missing(tauri_plugin_i18n_next::missing) // Rust misses into the dev report
.build()?;
tauri::Builder::default()
.plugin(tauri_plugin_i18n_next::Builder::new(i18n).build())
.setup(|app| {
let quit = tauri::menu::MenuItem::new(app, "Quit", true, None::<&str>)?;
let i18n = app.i18n(); // derefs to I18n
i18n.bind(&quit, i18n.page("tray").text("quit")); // relabeled on every switch
println!("{}", i18n_next::t!("menu.quit")); // the plugin installed the catalog
Ok(())
})
At start the plugin installs the catalog as the global instance (unless one is installed already), applies the
saved locale and registers the protocol. In debug builds it also watches dir / lazy_dir files and collects
missing keys. app.i18n() returns a Handle that derefs to I18n; app.state::<I18n>() works too.
Embed the files as above for release bundles: see Platforms.
| Builder option | Default | Effect |
|---|---|---|
system_locale(bool) | true | the first start picks the best of the WebView's navigator.languages |
persist(bool) | true | saves the active locale to i18n-next.json and applies it at the next start |
global(bool) | true | installs the catalog for t! |
watch(bool) | true | debug builds: reload on file changes; windows and bound labels update |
data_dir(path) | app config / data dir | where i18n-next.json and the dev i18n-missing.json go |
origins(iter) | none | more origins the protocol answers, see Origins |
Start locale
- The saved locale, if the catalog still has it and it is not disabled.
- Else the best match for the WebView's
navigator.languages. - Else the catalog's start locale (
Builder::locale, elsedefaultLocaleofi18n.json).
Rust shows dates in the WebView's time zone unless the catalog sets its own time_zone, so both sides print the same.
Native labels: bind
let i18n = app.i18n();
let id = i18n.bind(&window, i18n.text("window.title"));
i18n.bind(&tray_icon, i18n.page("tray").text("tooltip")); // plugin feature `tray-icon`
i18n.unbind(id);
bind sets the label now and after every change, until unbind. Targets: MenuItem, CheckMenuItem,
IconMenuItem, Submenu, Window, WebviewWindow, the tray tooltip, or your own type through the Relabel trait.
A destroyed target is unbound by itself.
Commands
A command can return a Text: it is sent as the string in the active locale.
#[tauri::command]
fn greeting(app: tauri::AppHandle, name: String) -> i18n_next::Text {
app.i18n().text("greeting").arg("name", name)
}
Frontend: Vue
import { createTauriI18n } from 'tauri-plugin-i18n-next-api/vue'
app.use(router)
app.use(await createTauriI18n({ router, maxPages: 20 }))
<script setup lang="ts">
import { useI18n } from '@i18n-micro/vue'
import { useI18nLink } from 'tauri-plugin-i18n-next-api/vue'
const { t } = useI18n()
const link = useI18nLink()
const sum = 42.5
</script>
<template>
<i18n-t keypath="cart.total" :number="sum" />
<button @click="link.setLocale('de')">{{ t('lang.de') }}</button>
</template>
$t,$tc,<i18n-t>anduseI18n()are those of@i18n-micro/vue, as in nuxt-i18n-micro.- Options: everything
createI18nof@i18n-micro/vuetakes exceptlocale,fallbackLocale,locales,defaultLocaleandmessages(Rust owns them), plusrouter,pageOfand theconnectoptions below. - Locales and named formats (
$tn(n, 'currency'),$td(d, 'short')) come fromi18n.jsonthrough Rust. - The router loads a route's page before the route shows, so raw keys never flash. The page is the route name
(
pageOfchanges that); a route without a page folder reads the root. A load error keeps what is shown. app.unmount()closes the link and removes the router hooks (plugin.dispose()without an app).
Frontend: connect
For any @i18n-micro instance:
import { createI18n } from '@i18n-micro/runtime'
import { connect } from 'tauri-plugin-i18n-next-api'
const i18n = createI18n({ locale: 'en' })
const link = await connect(i18n, { page: 'index', maxPages: 20 })
await link.setPage('settings') // load the page, then show it
await link.setLocale('de') // Rust, native labels and every window
await link.preload('about') // load without showing; kept for every locale
await link.load('about') // load for a navigation about to be confirmed
link.close() // stop following changes
| Option | Effect |
|---|---|
page | the page to show first |
maxPages | keep at most that many pages; the current and preloaded ones stay |
transport | 'auto' (default: the protocol, else the load command), 'protocol' or 'invoke' |
document | null stops setting <html lang dir> |
reportMissing | send misses to the dev report |
The Link has locale, page, version, meta and fallback (true while the load command carries the data),
and setPage, setLocale, preload, load, refresh, close. Each method waits for the ones before it.
connect merges each page along the fallback chain, so JS t() answers what Rust t answers. Full signatures:
JavaScript API, Types.
React, Preact, Solid
Their adapters build an @i18n-micro/runtime instance: hand it to connect and to the provider.
import { createI18n, I18nProvider, useT } from '@i18n-micro/react' // or /preact, /solid
import { connect, type I18nInstance } from 'tauri-plugin-i18n-next-api'
const i18n = createI18n({ locale: 'en' })
const link = await connect(i18n as unknown as I18nInstance)
root.render(<I18nProvider i18n={i18n}><App /></I18nProvider>)
// on navigation (your router's hook): await link.setPage(name)
The cast is needed because the adapters' types are wider than I18nInstance.
Switching the locale
link.setLocale(code) (or useI18n().locale.value = code in Vue) and app.i18n().set_locale(code) in Rust do the
same: Rust, every bound label and every window switch. Each window loads its texts in the new locale; the old texts
stay until the new ones are in. A locale Rust refuses puts the shown one back.
Events
| Event | Payload | When |
|---|---|---|
i18n-next://changed (EVENT_CHANGED) | { locale, version } | after a locale switch, add_messages, reload, a dev file reload |
i18n-next://missing (EVENT_MISSING) | { locale, page, key, count } | dev: a key missed for the first time |
The JS package already follows changed; listen yourself only for your own needs. IPC commands:
Commands.
Missing keys in dev
In debug builds the plugin collects misses from the frontend and from Rust (when the catalog is built with
.missing(tauri_plugin_i18n_next::missing)). Each key is counted once, written to i18n-missing.json in the app data
dir and announced with i18n-next://missing. The frontend needs i18n-next:allow-report-missing in a dev
capability. Release builds collect nothing.
Permissions
i18n-next:default allows everything the frontend needs except report_missing. Full list:
Permissions.
Content Security Policy
With app.security.csp set, allow the protocol in both spellings (the second is for Windows and Android):
{
"app": {
"security": {
"csp": {
"default-src": "'self'",
"connect-src": "ipc: http://ipc.localhost i18n-next: http://i18n-next.localhost"
}
}
}
}
Without it the frontend falls back to the load command: it still works, without the HTTP cache. A Rust frontend
(wasm) also needs 'wasm-unsafe-eval' in script-src.
Origins
The protocol answers the app's own origins and, in debug builds, the dev server. Pages served from elsewhere need
origins:
tauri_plugin_i18n_next::Builder::new(i18n)
.origins(["http://localhost:1430"]) // scheme, host and port; no path
.build()
Typed keys
@i18n-micro/types-generator reads the same locale folder and types every key of $t, t() and
<i18n-t keypath>:
import { I18nTypesPlugin } from '@i18n-micro/types-generator'
export default defineConfig({
plugins: [vue(), I18nTypesPlugin({ srcDir: import.meta.dirname, translationDir: '../locales', outputFile: 'src/i18n-micro.d.ts' })],
})
The generated file is rewritten on every build; keep it out of git.