Created
July 2, 2025 02:04
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i18next in NativeScript
Dependencies
Folder Structure
Installation
services
inapp
i18n.js
inservices
folderi18n
andjson lang
Example: en.json
Example: id.json
i18n.js
service inapp.js
ormain.ts
How to translate in page
example-page.js
example-page.xml
How to change language