【问题标题】:node.js i18n - Cannot read property 'toLowerCase' of undefinednode.js i18n - 无法读取未定义的属性“toLowerCase”
【发布时间】:2018-10-31 09:23:26
【问题描述】:

我在调用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)); 

locales/de.json

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

locales/en.json

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

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

【问题讨论】:

    标签: node.js i18n-node


    【解决方案1】:

    调用__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 对象上强制使用当前语言环境解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 2020-07-23
      • 2020-06-24
      • 2018-10-23
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      相关资源
      最近更新 更多