4

调用时我总是收到以下错误i18n.__n('..')

TypeError: Cannot read property 'toLowerCase' of undefined
at Object.i18nTranslatePlural [as __n] (/home/runner/node_modules/i18n/i18n.js:367:31)
at evalmachine.<anonymous>:14:18
at Script.runInContext (vm.js:74:29)
at Object.runInContext (vm.js:182:6)
at evaluate (/run_dir/repl.js:133:14)
at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
at ReadStream.emit (events.js:180:13)
at addChunk (_stream_readable.js:274:12)
at readableAddChunk (_stream_readable.js:261:11)
at ReadStream.Readable.push (_stream_readable.js:218:10)

顺便说一句,i18n.__('..')像魅力一样工作!

这是代码:

index.js

var i18n = require("i18n");
var path = require('path');

var __dirname = path.resolve();

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

console.log(i18n.__('test'));

console.log(i18n.__n('%s horse', 3)); 

语言环境/de.json

{
  "test": "Das ist ein Test",
  "%s horse" : {
    "one": "%s Pferd",
    "other": "%s Pferde"
  }
}

语言环境/en.json

{
  "test": "This is a test",
  "%s horse" : {
    "one": "%s horse",
    "other": "%s horses"
  }
}

希望有人能给我建议我做错了什么或如何解决问题。我在我的 mac book 和https://repl.it/languages/nodejs上运行了代码。结果相同。

4

1 回答 1

3

调用__n. 只需设置即可i18n.setLocale('de')。如下所示的代码将输出

Das ist ein Test
1 Pferd
3 Pferde

我原以为 defaultLocale 就足够了,但似乎不行。希望这个答案有帮助!

var i18n = require("i18n");
var path = require('path');

var __dirname = path.resolve();

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

});

i18n.setLocale('de')
console.log(i18n.__('test'));
console.log(i18n.__n("%s horse", 1));
console.log(i18n.__n("%s horse", 3));

仅供参考,我通过在configure()调用中注册一些类似这样的调试功能来调试它

logDebugFn: console.log,
logWarnFn: console.log,
logErrorFn: console.log

然后,没有setLocale()电话我得到了这个WARN: No locale found - check the context of the call to __(). Using de as current locale。在对象上强制使用当前语言环境i18n解决了这个问题。

于 2018-11-01T15:11:15.483 回答