Adding Multi-language Support to NativeScript

multilanguage

How to add multi-language support to NativeScript apps

If your app targets users from different parts of the world, these users might like to use your app in their own language. Creating a multilingual app is not an easy task because it requires additional work, but it will certainly allow your app to reach a bigger audience. NativeScript itself doesn’t provide any built-in features to help you with this. However, there are some third-party plugins that you can use.

Here’s how you can use nativescript-i18n plugin. It uses the native capabilities of each platform without requiring a separate JS or JSON file.

Setup

The first step is to install the plugin in your app:

npm install --save nativescript-i18n

Than we create a folder i18n in the app folder with the following structure:

i18n
|
|-- en
|              |- strings.xml
|
|-- fr
|- strings.xml

In app.js, we require nativescript-i18n and globals as early as possible. The best approach is to do it even before you require the application module, as the very first two lines.

require('globals');
require('nativescript-i18n');

Usage

The simplest way to use it in xml is like this:

<Label text="{{ L('hello') }}">

This plugin supports one or multiple replacements. Replacements can be hard coded string values or variables from the view model.

View.xml

<Label text="{{ L('hello') }}" class="title" textWrap="true" />
<Label text="{{ L('hello_replace','my friend') }}" class="message" textWrap="true" />
<Label text title="{{ L('multi_replace','direct replacement', modelReplacement) }}">

Strings.xml

<string name="hello">Hello!</string>
<string formatted="false" name="hello_replace">Hello %s!</string>
<string formatted="false" name="multi_replace">We can replace directly in xml: %s or from the model: %s</string>

Configuration

If for some reason you want to define a custom path for the i18n files (other than app /i18n), add this configuration to your project’s package.json:

"nativescript-i18n": {
"customLangPath": "app/resources/i18n"
}

The language will default to English if the phone’s language doesn’t match any of your defined languages. If you want to set your own default language, you can add this configuration to your project’s package.json:

"nativescript-i18n": {
"defaultLang": "fr"
}