6

我已经成功实现了 i18next,顺便说一句,这是一个很棒的库!尽管我仍在寻找“最佳实践”。这是我现在的设置,总的来说我喜欢:

var userLanguage = 'en'; // set at runtime

i18n.init({
    lng                 : userLanguage,
    shortcutFunction    : 'defaultValue',
    fallbackLng         : false,
    load                : 'unspecific',
    resGetPath          : 'locales/__lng__/__ns__.json'
});

在 DOM 中,我做这样的事情:

<span data-i18n="demo.myFirstExample">My first example</span>

在 JS 中,我会做这样的事情:

return i18n.t('demo.mySecondExample', 'My second example');

这意味着我在代码本身中维护英文翻译。translation.json但是,我使用 i18next-parser使用单独的文件维护其他语言:

gulp.task('i18next', function()
{
    gulp.src('app/**')
        .pipe(i18next({
            locales : ['nl','de'],
            output  : '../locales'
        }))
        .pipe(gulp.dest('locales'));
});

这一切都很好。唯一的问题是,当我设置'en'为 时userLanguagei18next坚持获取/locales/en/translation.json文件,即使它不包含任何翻译。{}为了防止 404,我目前在该文件中提供了一个空的 json 对象。

有没有办法完全防止加载空的 .json 文件?

4

3 回答 3

4

也许我在这里遗漏了一些东西,但你不能简单地这样做:

if (userLanguage != 'en') {

    i18n.init({
        lng                 : userLanguage,
        shortcutFunction    : 'defaultValue',
        fallbackLng         : false,
        load                : 'unspecific',
        resGetPath          : 'locales/__lng__/__ns__.json'
    });
}

这样,除非您确实需要翻译服务,否则您的脚本 i18n 不会被初始化。

于 2014-10-29T18:47:18.070 回答
4

i18next-parser author here, I will explain how I use i18next and hopefully it will help:

1/ I do not use defaultTranslation in the code. The reason is that it doesn't belong in the code. I understand the benefit of having the actual text but the code can get bloated quickly. The difficult part consists in defining intelligible translation keys. If you do that, you don't really need the defaultTranslation text anymore. The translation keys are self-explainatory.

2/ If you have a 404 on the /locales/en/translation.json, then probably that you don't have the file in your public directory or something similar. With gulp you can have multiple destination and do dest('locales').dest('public/locales') for instance.

3/ If there is no translation in the catalog, make sure you run the gulp task first. Regarding populating the catalog with the defaultTranslation you have, it is a tricky problem to solve with regexes. Think of this case <div data-i18n="key">Default <div>translation</div></div>. It needs to be able to parse the inner html and extract all the content. I just never took the time to implement it as I don't use it.

于 2014-12-16T15:16:45.227 回答
2

请参阅“初始化时允许使用的白名单语言”下的http://i18next.com/pages/doc_init.html(不能在这些文档上分段链接......):

i18n.init({ lngWhitelist: ['de-DE', 'de', 'fr'] });

仅允许加载指定的语言。

那应该可以解决您的问题。虽然我认为黑名单会更好。

于 2014-11-04T14:37:23.323 回答