Ir al contenido
Works with lefine

Título

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

Título

Una app móvil no puede publicar la corrección de un texto como lo hace un sitio web: cada versión pasa por la revisión de la tienda, los usuarios se quedan en versiones antiguas y la red nunca está garantizada.

  • Mantener un tamaño reducido del paquete de traducción para agilizar la descarga de la aplicación
  • Compatibilidad con el uso «offline-first» cuando no hay conexión a Internet
  • Gestión de formatos específicos de cada plataforma para fechas, números y divisas en iOS frente a Android
  • Implementación de la compatibilidad con el diseño de derecha a izquierda para el árabe, el hebreo y otros idiomas que se escriben de derecha a izquierda
  • Mantener los enlaces profundos y la navegación adaptados a la configuración regional en todas las pantallas de la aplicación

Título

React Native refleja los diseños para el árabe, el hebreo y otros idiomas RTL mediante I18nManager, pero un cambio de dirección solo surte efecto después de que la app se recarga, así que decida la dirección antes de que se renderice la primera pantalla.

Use start y end en lugar de left y right en sus estilos, y revise los iconos y gestos que implican una dirección. Las traducciones en sí no necesitan nada especial: un locale RTL se entrega desde la CDN como cualquier otro.

Get started

Comienza gratis.