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

Viewed 2961

I have an existing Vue project, and I'm adding localization to it with the i18n plugin. Everything installed properly, and according to everything I've read (see here), I have everything installed correctly. This includes one file per locale under /src/locales with the name of the locale as the file name (/src/locales/en.json).

The contents of the /src/i18n.js file are:

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(),
});

The error I am running into is inside loadLocaleMessages(), where it is attempting to load the /src/locales/.json files. I stepped through it in a debugger, and at

messages[locale] = locales(key);

it throws the error

Cannot find module './en.json'

where key = ./en.json and locale = en.

As far as I can tell, I'm doing everything correct. What am I missing that is causing this error?

2 Answers

Well, as embarrassing as it is to admit this, the issue all along was a trailing comma in my en.json file. I had

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

instead of

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

probably because I'm so used to eslint forcing trailing commas in my JS code.

When all else fails, take notice of compilation errors in your IDE...

I had the same error but was because I created the Json file but never put any content.

Just in case It also happens to you.

Related