i18n-node icon indicating copy to clipboard operation
i18n-node copied to clipboard

__n() throws error if setLocale not called, despite defaultLocale

Open ucacoin opened this issue 5 years ago • 4 comments

HI,

if you call __n() without setLocale beforehand it will throw:

var lc = targetLocale.toLowerCase().split(/[_-\s]+/)
                              ^

TypeError: Cannot read property 'toLowerCase' of undefined
    at Object.i18nTranslatePlural [as __n] (path/node_modules/i18n/i18n.js:371:31)
    at Module._compile (internal/modules/cjs/loader.js:1147:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Module._compile (internal/modules/cjs/loader.js:1147:30)

Even if you define a default locale with:

i18n.configure({
    locales:['en', 'de'],
    directory: __dirname + '/../locales',
    defaultLocale: 'de',
});

There should be a fallback that if no targetLocale is found the defaultLocale should be used.

ucacoin avatar Apr 03 '20 18:04 ucacoin

Maybe you can add some code to reproduce your setup?

mashpie avatar Aug 19 '20 14:08 mashpie

I don't have a project setup, but I was able to reproduce the issue with

const path = require('path');
const {I18n} = require('i18n');
const i18n = new I18n({
    locales: ['en', 'es'],
    directory: path.join(__dirname, '..', '..', 'locales'),
});

let {__n} = i18n;
__n('%s cats', 1);

This can be fixed by doing

let {__n} = i18n;
__n = __n.bind(i18n);
__n('%s cats', 1);

edit: I missed this fix I had locally. seems that you must set the locale before using __n as well.

let {__n} = i18n;
i18n.setLocale('en');
__n = __n.bind(i18n);
__n('%s cats', 1);

latagore avatar May 15 '21 22:05 latagore

Adding setLocale was enough for me just after initializing I18n.

const i18n = new I18n({ ... })
i18n.setLocale('en')

beytarovski avatar Jul 13 '22 14:07 beytarovski