Vai al contenuto
Works with lefine

Titolo

lefine runs in React Native and Expo today: lefine/server loads the texts, lefine/react shows them. Hermes needs one polyfill for plurals.

Package
lefine
Entry
lefine/server · lefine/react
Plurals
@formatjs/intl-pluralrules
lefine
01Terminale
npm install lefine @formatjs/intl-pluralrules expo-localization @react-native-async-storage/async-storage
02index.ts
// index.ts, before anything else: Hermes has no Intl.PluralRules.// Add the polyfill and the rules of each language the app ships.import "@formatjs/intl-pluralrules/polyfill-force.js";import "@formatjs/intl-pluralrules/locale-data/en.js";import "@formatjs/intl-pluralrules/locale-data/de.js";
03App.tsx
// App.tsximport { useEffect, useState } from "react";import AsyncStorage from "@react-native-async-storage/async-storage";import { getLocales } from "expo-localization";import { StringsProvider } from "lefine/react";import { createStrings, type StringsProps } from "lefine/server"; // runs anywhere: no Node or React inside// One per app. storage keeps the last manifest and language files on the device,// so a cold start shows texts at once, with or without a network.// MMKV works too: { get: async (k) => mmkv.getString(k), set: async (k, v) => mmkv.set(k, v) }const strings = createStrings({  project: "app_...",  storage: { get: (k) => AsyncStorage.getItem(k), set: (k, v) => AsyncStorage.setItem(k, v) },});// The device's first language the app publishes ("de-DE" finds "de"), else the first published one.async function pickLocale() {  const published = (await strings.languages()).map((l) => l.code);  for (const { languageTag } of getLocales()) {    const tag = languageTag.toLowerCase();    const hit = published.find((c) => c === tag) ?? published.find((c) => c === tag.split("-")[0]);    if (hit) return hit;  }  return published[0]!;}export default function App() {  const [props, setProps] = useState<StringsProps | null>(null);  useEffect(() => {    pickLocale().then((locale) => strings.load(locale, ["home"])).then(setProps);  }, []);  return props ? (    <StringsProvider {...props}>      <Home />    </StringsProvider>  ) : null;}
04Home.tsx
// Home.tsximport { Text } from "react-native";import { useStrings } from "lefine/react";export function Home() {  const t = useStrings("home");  return <Text>{t("greeting", { name: "World" })}</Text>;}
t("greeting", { name: "World" })
Hello, World
01/Setup

Set it up

  1. 01

    Install

    lefine, the plural rules for Hermes, expo-localization for the device language, and AsyncStorage for the offline copy.

    terminalbash
    npm install lefine @formatjs/intl-pluralrules expo-localization @react-native-async-storage/async-storage
  2. 02

    Add the plural polyfill

    Hermes has no Intl.PluralRules. Without the polyfill, lefine picks “one” for 1 and “other” for the rest, and in development the console names the package.

    index.ts
    // index.ts, before anything else: Hermes has no Intl.PluralRules.// Add the polyfill and the rules of each language the app ships.import "@formatjs/intl-pluralrules/polyfill-force.js";import "@formatjs/intl-pluralrules/locale-data/en.js";import "@formatjs/intl-pluralrules/locale-data/de.js";
  3. 03

    Load the texts, with a copy on the device

    createStrings takes your app id and a storage ({ get, set }). After each download lefine saves the file on the device. On a cold start, load serves that copy at once and asks the edge in the background; the next load has the new texts.

    App.tsx
    // App.tsximport { useEffect, useState } from "react";import AsyncStorage from "@react-native-async-storage/async-storage";import { getLocales } from "expo-localization";import { StringsProvider } from "lefine/react";import { createStrings, type StringsProps } from "lefine/server"; // runs anywhere: no Node or React inside// One per app. storage keeps the last manifest and language files on the device,// so a cold start shows texts at once, with or without a network.// MMKV works too: { get: async (k) => mmkv.getString(k), set: async (k, v) => mmkv.set(k, v) }const strings = createStrings({  project: "app_...",  storage: { get: (k) => AsyncStorage.getItem(k), set: (k, v) => AsyncStorage.setItem(k, v) },});// The device's first language the app publishes ("de-DE" finds "de"), else the first published one.async function pickLocale() {  const published = (await strings.languages()).map((l) => l.code);  for (const { languageTag } of getLocales()) {    const tag = languageTag.toLowerCase();    const hit = published.find((c) => c === tag) ?? published.find((c) => c === tag.split("-")[0]);    if (hit) return hit;  }  return published[0]!;}export default function App() {  const [props, setProps] = useState<StringsProps | null>(null);  useEffect(() => {    pickLocale().then((locale) => strings.load(locale, ["home"])).then(setProps);  }, []);  return props ? (    <StringsProvider {...props}>      <Home />    </StringsProvider>  ) : null;}
  4. 04

    Use them in a screen

    The same useStrings as on the web. ICU plurals, selects and numbers work.

    Home.tsx
    // Home.tsximport { Text } from "react-native";import { useStrings } from "lefine/react";export function Home() {  const t = useStrings("home");  return <Text>{t("greeting", { name: "World" })}</Text>;}
02/Notes

Before you ship

  • Offline starts need one online start first: a language never loaded online is not on the device, and load throws for it while offline. lefine does not invent texts.
  • A device copy is checked before use (its version and key count must match the saved manifest). A store that throws counts as an empty cache.
  • lefine does not pick the device language for you. Use expo-localization (or any locale library) and pass a published language to load.
  • On Hermes there is no crypto.subtle, so the file's sha256 is not checked there. The key count is still checked, and an empty file is refused.
03/Capabilities

What works

  • Checked in Expo Go (SDK 58, React Native 0.88) on the iOS simulator, and in an Android export to Hermes bytecode.
  • No native module: lefine and the polyfill are plain JavaScript.
  • The same StringsProvider and useStrings as a React web app.
  • Texts come from the Lefine edge by app id, so a publish reaches the app without a store release.
  • Offline starts: with storage, a cold start with the edge away shows the last texts it saved. Checked in Expo Go with AsyncStorage.
04/FAQ

FAQ

Do I need a native module?
No. lefine is plain TypeScript, and the plural polyfill is JavaScript. It was checked in Expo Go, which runs no custom native code.
Why the polyfill?
Hermes, the engine of React Native, has no Intl.PluralRules. Without it a plural like “2 messages” cannot pick its form. With @formatjs/intl-pluralrules and the rules of your languages, plurals follow each language.
Does it work offline?
Yes, with storage. Pass AsyncStorage or MMKV as { get, set } to createStrings: lefine saves each verified file on the device and serves it on a cold start, online or not, then refreshes in the background. A language the app never loaded online is not there yet.
05/Challenges

Titolo

Un’app mobile non può rilasciare la correzione di una stringa come fa un sito web: ogni release passa dalla revisione dello store, gli utenti restano su versioni vecchie e la rete non è mai garantita.

  • Mantenere ridotte le dimensioni dei pacchetti di traduzione per garantire download rapidi delle app
  • Supporto dell'utilizzo "offline-first" quando la rete non è disponibile
  • Gestione dei formati specifici per piattaforma relativi a date, numeri e valute su iOS e Android
  • Implementazione del supporto per la scrittura da destra a sinistra per l'arabo, l'ebraico e altre lingue RTL
  • Mantenimento di collegamenti diretti e navigazione sensibili alle impostazioni locali tra le schermate dell'app

Titolo

React Native rispecchia i layout per arabo, ebraico e altre lingue RTL tramite I18nManager, ma un cambio di direzione ha effetto solo dopo il ricaricamento dell’app, quindi decida la direzione prima che venga renderizzata la prima schermata.

Usi start ed end invece di left e right nei suoi stili, e controlli le icone e i gesti che implicano una direzione. Le traduzioni in sé non richiedono nulla di speciale: una lingua RTL viene distribuita dal CDN come qualsiasi altra.

Get started

Inizia gratis.