mashpie / i18n-node

Lightweight simple translation module for node.js / express.js with dynamic json storage. Uses common __('...') syntax in app and templates.
MIT License
3.08k stars 419 forks source link

defaultLocale not change after setLocale #471

Closed yogeshp-iprogrammer closed 3 years ago

yogeshp-iprogrammer commented 3 years ago

Hello @mashpie , I tried following code. I got default locale text. If I'm wrong, guide me, Thanks in advance :)

en_US.json

{ "label_password": "password" }


es_ES.json

{ "label_password": "contraseña" }


i18nConfig.ts

import i18n from 'i18n'; import path from 'path';

i18n.configure({ locales: ['en_US', 'es_ES'], defaultLocale: 'en_US', directory: path.resolve('./assets/locales/', 'i18n') }); i18n.setLocale('en_US);

export default i18n;


schema.ts

import i18n from './i18nConfig'; export const pin i18n.__('label_password');


middleware.ts

import i18n from './i18nConfig' import {testparam} from './schema'; const locale = 'es_ES'; i18n.setLocale(locale); console.log(testparam); // get english password instead of spanish

mashpie commented 3 years ago

you need to bind the i18n instance to an object that handles current locales and i18n's state: https://github.com/mashpie/i18n-node#some-words-on-register-option

in most use cases this would be the req and/or res object of any incoming http request. But you can use any other object too.

yogeshp-iprogrammer commented 3 years ago

you need to bind the i18n instance to an object that handles current locales and i18n's state: https://github.com/mashpie/i18n-node#some-words-on-register-option

in most use cases this would be the req and/or res object of any incoming http request. But you can use any other object too.

Thanks for replying. I changed my code as per your suggestion but this default language does not change. Initially, the file #schema.ts was loaded first then I called setlocale but the first value may not override or I am still doing it wrong.

mashpie commented 3 years ago

well the defaultLanguage won't change ever. It's purpose is to define a language for all unknown incoming requests locales. Say you have translations ready for en and no and set your defaultLanguage to en.

yogeshp-iprogrammer commented 3 years ago

Thanks, @mashpie