错误 - "Cannot find module ./en.json" 使用 vue-i18n 插件

Error - "Cannot find module ./en.json" using vue-i18n plugin

我有一个现有的 Vue 项目,我正在使用 i18n 插件为其添加本地化。一切都已正确安装,并且根据我阅读的所有内容(参见 here),我已正确安装了一切。这包括 /src/locales 下的每个区域设置一个文件,文件名是区域设置的名称 (/src/locales/en.json)。

/src/i18n.js 文件的内容是:

import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

function loadLocaleMessages() {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
  const messages = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages(),
});

我 运行 遇到的错误是在 loadLocaleMessages() 中,它试图加载 /src/locales/.json 文件。我在调试器中逐步完成它,并在

messages[locale] = locales(key);

它抛出错误

Cannot find module './en.json'

其中 key = ./en.jsonlocale = en.

据我所知,我做的一切都是正确的。我错过了什么导致了这个错误?

好吧,承认这一点很尴尬,问题一直是我的 en.json 文件中的尾随逗号。我有

{
  "message": "hello i18n !!",
}

而不是

{
  "message": "hello i18n !!"
}

可能是因为我已经习惯了在我的 JS 代码中使用 eslint 强制尾随逗号。

当所有其他方法都失败时,请注意 IDE...

中的编译错误

我遇到了同样的错误,但这是因为我创建了 Json 文件但从未放入任何内容。

以防万一你也遇到了