I recently integrated the i18n plugin into my existing Vue project to add localization. After following all the installation instructions from various sources (such as here), I made sure that each locale has its own file under /src/locales
with the correct naming convention (/src/locales/en.json
).
The code snippet from my /src/i18n.js
file looks like this:
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(),
});
However, when running the code, an error occurs within the loadLocaleMessages()
function while trying to load the /src/locales/.json
files. Specifically, the error is thrown at this line:
messages[locale] = locales(key);
An error message pops up saying:
Cannot find module './en.json'
With key
set to ./en.json
and locale
being en
, it seems like everything should be working correctly. Can anyone pinpoint what might be causing this particular error?