我有一个现有的 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.json
和 locale
= en
。
据我所知,我所做的一切都是正确的。我错过了什么导致这个错误?
最佳答案
嗯,虽然承认这一点很尴尬,但问题始终是我的 en.json
文件中的尾随逗号。我有
{
"message": "hello i18n !!",
}
而不是
{
"message": "hello i18n !!"
}
可能是因为我太习惯在 JS 代码中使用 eslint 强制添加尾随逗号。
当所有其他方法都失败时,请注意 IDE 中的编译错误...
关于javascript - 使用 vue-i18n 插件时出现错误 - "Cannot find module ./en.json",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60679514/