我将 i18next 与打字稿一起使用,并使用 i18next-resources-for-ts 从 JSON 生成资源类型以及翻译资源。一切正常,但在将前缀命名空间与
t
挂钩中的 useTranslation()
函数一起使用时,我遇到了问题。我不是在寻找 useTranslation('common')
或 t('auth.login.text', { ns: 'common' })
,它们工作正常并且输入正确。
这是我的
i18next.d.ts
的简化版本:
import 'i18next';
import common from '../public/locales/en/common.json';
const resources = {
common,
} as const;
declare module 'i18next' {
interface CustomTypeOptions {
returnNull: false;
defaultNS: 'common';
resources: typeof resources;
}
}
并设置
i18next.ts
import commonDe from '../public/locales/de/common.json';
import commonEn from '../public/locales/de/common.json';
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
const resources = {
de: {
common: commonDe,
},
en: {
common: commonEn,
},
};
export const defaultNS = 'common';
i18next
.use(initReactI18next)
.init({
resources,
ns: [defaultNS],
defaultNS,
lng: 'en',
interpolation: {
escapeValue: false,
},
returnNull: false,
});
export default i18next;
尝试在
t
函数中使用前缀命名空间时会出现问题:
const { t } = useTranslations();
t('common:auth.login.text')
然后类型就不起作用了。
我知道我可以指定
ns
作为 t
函数的选项,或者已经在 useTranslation
挂钩中选择它。但我也想在翻译键中支持上面的前缀方式。
任何有关如何实现这一目标的建议或想法将不胜感激。谢谢!
您的问题似乎是将默认 ns 设置为常见。这使得你的翻译路径
t('common:common:auth.login.text')
如果你删除defaultNS它应该可以工作。
export const defaultNS = 'common';
或者删除 common 也可以解决问题。
t('auth.login.text')
我认为你的翻译文件看起来像 tihs。
common.json
{
"auth": {
"login": {
"text": "This is a text"
}
}
}
如果您需要可重现的示例,请告诉我。