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 the Nativescript-i18n plugin.
It uses the native capabilities of each platform without requiring a separate JS or JSON file.
Table of Contents
Setup
The first step is to install the plugin in your app.
npm install --save nativescript-i18n
Then, 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" }
Conclusion
Expanding your app to support multiple languages is a worthwhile investment for reaching a broader audience, whether it’s a desktop or mobile app.
Although NativeScript doesn’t offer built-in multilingual support, third-party plugins like NativeScript-i18n can help.
This plugin leverages each platform’s native capabilities, allowing for seamless localization.
By following the setup steps and configuring language preferences, you can enhance your app’s accessibility worldwide.
A well-localized app shows users that you value their experience, contributing to a more inclusive and engaging product.