Auxiliary library for localization
Auxiliary library for localization
The Tangl viewer supports multilingual interface.
The i18next library is used for this purpose. Locales to be used in Tangl and in the application itself are loaded into i18next object.
tangl-i18next-vite is a utility library for collecting locales from YML files from different sources at build stage using Vite.
Import
A general scheme of locale folders is shown below:
[vite-project]
├─ [locales] //all locales
│ ├─ [ru] //ru locales
│ │ ├─ global.yml //ru global scope locales
│ │ ├─ module1.yml //ru module scope locales
│ │ └─ module2.yml //ru module scope locales
│ └─ [en]
│ ├─ global.yml //en global scope locales
│ ├─ module1.yml //en module scope locales
│ └─ module2.yml //en module scope locales
├─ [src]
├─ vite.config.ts
└─ package.json
The root folder contains inner folders for each language that contain YML files with locales. Locales can be global or modular.
Create a generic folder structure with locales, download the library and put in dev dependencies in package.json:
npm i tangl-i18next-vite -D
Import the library into vite.config.ts and add the paths where the locales are in the project:
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import i18Next from 'tangl-i18next-vite'
const path = require('path');
export default defineConfig(() => {
return {
plugins: [
vue(),
i18Next({
include: [
path.resolve(__dirname, './locales/*/*.yml')
]
}),
]
}
})
Using
At the entry point of the index.ts, import the i18next object and the collected locales in the messages object:
import i18next from "i18next";
import messages from 'tangl-i18next-vite/messages'
Initialize the i18next object with the collected locales:
//need for i18next resources parsing
Object.keys(messages).forEach(function (key) {
messages[key] = ({"translation": messages[key]});
});
i18next.use(LanguageDetector).init({
fallbackLng: ["en", "ru"],
supportedLngs: ["en", "ru"],
lng: 'ru',
resources: messages
})
Use locales anywhere in the code:
i18next.t("module1.testLocale")