I am using vue-i18n in a Nuxtjs project, and I want to import my locale files with vite dynamicly.
when I am using webpack, those code run well
plugins/i18n.js
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import config from '@/config';
Vue.use(VueI18n);
let messages = Object;
config.locale.available.forEach(locale => {
messages[locale] = require(`~/locales/${locale}.json`);
});
export default ({ app, store }) => {
app.i18n = new VueI18n({
locale: store.state.locale.locale,
messages: messages
});
}
I got that there is no require()
in vitejs, also the glob-import feature of vitejs
- So I tried like this below first:
let messages = Object,
languages = import.meta.glob('../locales/*.json'); // => languages = {} (languages only get {} value)
config.locale.available.forEach(locale => {
messages[locale] = languages[`../locales/${locale}.json`];
});
But the languages
only got {}
value.
- Then I tried to use
import()
let messages = Object,
translate = lang => () => import(`@/locales/${lang}.json`).then(i => i.default || i);
config.locale.available.forEach(locale => {
messages[locale] = translate(locale);
});
no errors in both terminal and console, but no locale file has been loaded correctly.
only if I import()
one by one, the issue will disappear:
import en from '@/locales/en.json';
import fr from '@/locales/fr.json';
import ja from '@/locales/ja.json';
let messages = Object;
messages['en'] = en;
messages['fr'] = fr;
messages['ja'] = ja;
CodeSandbox
But, how to import it dynamicly?
I googled it, but helped little. Greate thank for anyone help!