【问题标题】:Why am I getting undefined with i18next handlebars为什么我在使用 i18next 车把时变得不确定
【发布时间】:2022-09-23 11:36:49
【问题描述】:
我使用带有把手的 i18next 得到一个未定义的变量名
以下是我初始化 i18next with this package 的代码:
const i18next = require(\'i18next\');
const HandlebarsI18n = require(\"handlebars-i18n\");
import resources from \"./i18n/messages\";
i18next.init({
resources,
debug: true,
fallbackLng: \"en\",
lng : \"en\"
});
HandlebarsI18n.init();
export default i18next;
在我编译了车把的 index.ts 中
import \"./i18n\"
我使用 i18next 的地方如下所示:
<span class=\"typography-h3\">{{__ getNodeLabel .}}{{#if attributes.required}}
<span class=\"required-indicator\">*</span>{{/if}}
</span>
如果我用{{__ \"Password\"}} 之类的东西替换{{__ getNodeLabel .}},我仍然不确定,不确定发生了什么。
标签:
handlebars.js
i18next
express-handlebars
next-i18next
【解决方案1】:
我相信这个问题与 handlebars-i18n 包的 package.json 中定义的 i18next peerDependency 有关。在最新版本的handlebars-i18n 中,i18next peerDependency 版本为^21.6.14。
假设您最近使用命令npm install i18next 将i18next 安装到您自己的项目中,您将在项目的package.json 中对i18next 有一个依赖关系,最新版本是^21.9.2。
我不是 npm 如何处理 peerDependencies 的专家,但似乎由于这两个版本之间的差异,^21.6.14 和 ^21.9.2,npm 正在安装这两个版本。
这意味着在您的项目的node_modules 文件夹中有两个版本的i18next - 一个位于node_modules (21.9.2) 的顶层,另一个位于node_modules/handlebars-i18n/node_modules (21.6.14)。
它是导致问题的两个版本。当您通过在代码中调用 i18next 来初始化 i18next 时,您正在初始化 21.9.2 版本。但是handlebars-i18n 加载了21.6.14 版本并且它永远不会被初始化并且所有对其翻译的调用,.t,方法返回undefined。
我可以通过卸载i18next 然后使用handlebars-i18n package.json 中定义的相同版本再次安装它来实现此功能:
npm uninstall i18next
npm install i18next@21.6.14
这样可以确保只安装一个i18next。