Aller au contenu
Works with lefine

Titre

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
01Terminal
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

Titre

Une application mobile ne peut pas livrer une correction de texte comme un site web : chaque version passe par la validation des stores, les utilisateurs restent sur d'anciennes versions et le réseau n'est jamais garanti.

  • Réduire la taille du pack de traduction pour accélérer le téléchargement de l'application
  • Prise en charge d'une utilisation privilégiant le mode hors ligne lorsque le réseau n'est pas disponible
  • Gestion des formats de date, de nombre et de devise spécifiques à chaque plateforme sur iOS et Android
  • Mise en place de la prise en charge de la mise en page de droite à gauche pour l'arabe, l'hébreu et d'autres langues s'écrivant de droite à gauche
  • Maintenir des liens profonds et une navigation adaptés aux paramètres régionaux sur l'ensemble des écrans de l'application

Titre

React Native inverse la mise en page pour l'arabe, l'hébreu et les autres langues RTL via I18nManager, mais un changement de direction ne prend effet qu'après le rechargement de l'application : décidez donc de la direction avant le rendu du premier écran.

Utilisez start et end plutôt que left et right dans vos styles, et vérifiez les icônes et les gestes qui impliquent une direction. Les traductions elles-mêmes ne demandent rien de particulier : une locale RTL est diffusée depuis le CDN comme n'importe quelle autre.

Get started

Commencez gratuitement.

Localisez votre application mobile

Sous-titre