i18next 服务未初始化 - 添加自定义格式化程序函数时在运行时"Cannot read properties of undefined (reading 'add')"



突然间,当执行以下代码(在services.formatter.add)时,我开始在运行时使用i18next(版本22.4.5)时出现错误:

"Uncaught TypeError: Cannot read properties of undefined (reading 'add')"

调试后,i18nextInstance上的services对象在初始化后为空({})(见截图),这会导致TypeError,但我找不到为什么这个对象现在为空。

const i18nextInstance = i18next.createInstance({
debug: true,
lng: currentLanguage,
fallbackLng: 'en-GB', // Fallback to English strings and don't show an error
fallbackNS: defaultNamespace, // Fallback for strings translated with `t`
defaultNS: defaultNamespace,
resources: resources
});
i18nextInstance.t('common:Hello World');
/**
* Formatter function for locale-specific relative time strings 
*/
i18nextInstance.services.formatter.add('fromnow', (value: Date, lng, options): string => {
return timeAgo(value, lng);
});

上周我正在使用这个版本的软件包,它的功能和预期的一样——是什么原因突然导致了这一切?我的同事运行同样的代码(我们都在Windows上),他有完全相同的问题。我只是在试图让组件代码Jest测试工作时遇到这个问题,但现在它出现在Chrome中。

对于上下文,我在StencilJS项目中使用这个库,在它自己的模块中,该模块在应用程序开始时被一些组件导入。

我尝试安装一个新版本的库(22.4.9),但是没有成功。

我已经尝试重置我的node_modules文件夹并重新安装库,以及删除所有与模板构建相关的文件夹(WWW, dist, loader)。

我在Chrome上硬重新加载了有问题的页面。

弄清楚了-原来createInstance没有初始化实例,所以我需要在createInstance之后添加init:


i18nextInstance.init();

这真的很奇怪,因为我以前不需要使用这个函数,但我猜可能有一些缓存?

相关内容

最新更新