Skip to content

Instantly share code, notes, and snippets.

@dyazincahya
Created July 2, 2025 02:04
Show Gist options
  • Save dyazincahya/0fac190eb47b1065f393d3db90c211dc to your computer and use it in GitHub Desktop.
Save dyazincahya/0fac190eb47b1065f393d3db90c211dc to your computer and use it in GitHub Desktop.
An alternative to @nativescript/localize for implementing multiple languages in NativeScript using i18next
import { ApplicationSettings, Device, Frame } from "@nativescript/core";
import i18next from "i18next";
// Import your translation files
import en from "../i18n/en.json";
import id from "../i18n/id.json";
/**
* Main translation function. We export it so it can be accessed from anywhere.
* 'L' is a common abbreviation for 'Localize' or 'Language'.
*/
export const L = i18next.t.bind(i18next);
/**
* Initialize the i18n service. Just call once when the app starts.
*/
export function init() {
// 1. Prioritize the user's saved language
const savedLanguage = ApplicationSettings.hasKey("userLanguage")
? ApplicationSettings.getString("userLanguage")
: null;
// 2. If not available, use device language
const deviceLanguage = Device.language.split("-")[0];
i18next.init({
debug: false, // Turn off in production mode
lng: savedLanguage || deviceLanguage,
fallbackLng: "en",
resources: {
en: en,
id: id,
},
});
console.log(`i18n Service Initialized. Language: ${i18next.language}`);
}
/**
* Function to switch language globally.
* @param langCode - Language code (e.g., 'en', 'id')
*/
export function switchLanguage(langCode) {
if (i18next.language === langCode) {
console.log(`Language is already ${langCode}, no change.`);
return;
}
// Save user preference for next session
ApplicationSettings.setString("userLanguage", langCode);
// Change language and refresh UI by re-navigating the page
i18next.changeLanguage(langCode).then(() => {
console.log(`Language changed to ${langCode}. Refreshing UI...`);
const topmost = Frame.topmost();
if (topmost) {
topmost.navigate(topmost.currentEntry);
}
});
}
/**
* Function to get the currently active language.
* @returns The active language code
*/
export function getCurrentLanguage() {
return i18next.language;
}
@dyazincahya
Copy link
Author

dyazincahya commented Jul 2, 2025

i18next in NativeScript

Dependencies

Folder Structure

NSProject/
├── app/
│   └── i18n/
│       └── en.json
│       └── id.json
│       └── fr.json
│       └── es.json
│       └── Etc...
│   └── services/
│       └── i18n.js
│   └── app.js
|

Installation

  1. Create new folder services in app
  2. Save i18n.js in services folder
  3. Create new folder i18n and json lang

Example: en.json

{
  "translation": {
    "title": "title",
    "content": "content"
  }
}

Example: id.json

{
  "translation": {
    "title": "judul",
    "content": "konten"
  }
}
  1. Load i18n.js service in app.js or main.ts
import { Application, Observable } from "@nativescript/core";
import * as I18nService from "./services/i18n";

// 1. Initialize i18n Service (just this one line)
I18nService.init();
// 2. [IMPORTANT PART] Automatically provide the 'L' function for all pages
// We use the 'displayed' event from Application which will be triggered every time a page is shown.
Application.on(Application.displayedEvent, (args) => {
  const page = args.object;
  // Check if the page has a bindingContext and does not yet have the L function
  if (page && (!page.bindingContext || !page.bindingContext.L)) {
    // Ensure bindingContext exists
    page.bindingContext = page.bindingContext || new Observable();
    // Add the L function to the page's bindingContext automatically
    page.bindingContext.L = I18nService.L;
  }
});

Application.run({ moduleName: "app-root" });

How to translate in page

example-page.js

import { ObservableArray } from "@nativescript/core";
import * as I18nService from "~/services/i18n";

const context = new ObservableArray([]);

export function onNavigatingTo(args) {
  const page = args.object;

  context.set("L", I18nService.L);

  page.bindingContext = context;
}

example-page.xml

<Page 
  navigatingTo="onNavigatingTo" 
  xmlns="http://schemas.nativescript.org/tns.xsd"
  actionBarHidden="true">

  <StackLayout>
    <Label text="{{ L('title') }}" />
    <Label text="{{ L('content') }}" />
  </StackLayout>
</Page>

How to change language

import * as I18nService from "~/services/i18n";

const lang = I18nService.getCurrentLanguage() === "id" ? "en" : "id";
I18nService.switchLanguage(lang);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment