Search code examples
handlebars.jsi18nextexpress-handlebarsnext-i18next

Why am I getting undefined with i18next handlebars


I am getting an undefined variable name using i18next with handlebars

Following is my code to init 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;

In my index.ts where I have the handlebars compiled I have import "./i18n"

Where I use the i18next looks like this:

<span class="typography-h3">{{__ getNodeLabel .}}{{#if attributes.required}}
   <span class="required-indicator">*</span>{{/if}}
</span>

If I replace the {{__ getNodeLabel .}} with something like {{__ "Password"}} I still get undefined not to sure what is up.


Solution

  • I believe the issue has to do with the i18next peerDependency defined in the package.json of the handlebars-i18n package. In the latest version of handlebars-i18n, the i18next peerDependency version is ^21.6.14.

    Assuming you have recently installed i18next into your own project with the command npm install i18next, you will have a dependency in your project's package.json for i18next with the latest version which is currently ^21.9.2.

    I am not an expert on how npm handles peerDependencies, but it seems that due to the differences between these two versions, ^21.6.14 and ^21.9.2, that npm is installing both.

    This means that in your project's node_modules folder there are two versions of i18next - one at the top-level of your node_modules (21.9.2) and one at node_modules/handlebars-i18n/node_modules (21.6.14).

    Its the two versions that cause the problem. When you initialize i18next by calling i18next in your code, you are initializing the 21.9.2 version. But handlebars-i18n loads the 21.6.14 version and it never gets initialized and all calls to its translate, .t, method return undefined.

    I was able to get this working by uninstalling i18next and then installing it again using the same version that is defined in the handlebars-i18n package.json:

    npm uninstall i18next
    npm install [email protected]
    

    This ensures that only one i18next is installed.