【问题标题】:Context is undefined in translation module翻译模块中未定义上下文
【发布时间】:2021-11-26 14:45:22
【问题描述】:

我尝试添加对端点的调用以获得翻译。我有这样的:

const loadLocales = async () => {
const context = require.context('./locales', true);
const data = await ApiService.post(`${translationToolUrl}/gateway/translations`, { project: 'myProject' });
const messages = context.keys()
.map((key) => ({ key, locale: key.match(/[-a-z0-9_]+/i)[0] }))
.reduce((msgs, { key, locale }) => ({
  ...msgs,
  [locale]: extendMessages(context(key)),
}), {});
return { context, messages };
};

const { context, messages } = loadLocales();

i18n = new VueI18n({
   locale: 'en',
   fallbackLocale: 'en',
   silentFallbackWarn: true,
   messages,  
});

if (module.hot) {
  module.hot.accept(context.id, () => {
  const { messages: newMessages } = loadLocales();
  Object.keys(newMessages)
    .filter((locale) => messages[locale] !== extendMessages(newMessages[locale]))
    .forEach((locale) => {
       const msgs = extendMessages(newMessages[locale]);
       messages[locale] = msgs;
       i18n.setLocaleMessage(locale, msgs);
     });
  });
  }

我添加了这个请求:ApiService.post。但是我有错误TypeError: context is undefined 掉在了module.hot.accept(context.id... 这一行。你知道我该如何解决吗?我的范围是添加此请求,以便暂时从数据库和 .json 文件中获取翻译。我现在想在两者之间进行合并,我将只从数据库中获取该功能,但这将逐步完成。

【问题讨论】:

    标签: javascript vue.js vuejs2 i18next


    【解决方案1】:

    问题是,您尝试以错误的方式声明多个const,而与尝试声明它们两次无关。这显示在:

    const { context, messages } = loadLocales();
    

    这将使contextmessages 成为undefined。正如我在一个小示例中复制的那样,这不会产生错误:

    const {first, second} = 'Testing'
    console.log(first)
    console.log(second)
    

    firstsecond 都将是 undefined。如果你尝试一次声明多个const,你需要这样做:

    const context = loadLocales(), messages = loadLocales();
    

    【讨论】:

    • 我猜这个问题与等待和异步有关。
    • @klsdskldsd 你的错误是context is undefined,这就是它所说的。当您尝试在 module.hot.accept(context.id,... 中调用未定义的 context 时,您会收到此错误。
    • 谢谢。如果我确实像你说的那样:const context = loadLocales(); const messages = loadLocales(); console.log(messages); 我在控制台中有:Promise { <state>: "pending" }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2021-04-22
    相关资源
    最近更新 更多