Hey,
is there a way to import external languages files?
Let my config.js hold all the language-strings seems a little bit unlucky. I tried to import files via require() but then I got compiler errors from gulp.
Here is my config.js:
...
var VueI18n = require('vue-i18n');
/*
This becomes very confusing when there are many strings
var locales = {
de: {
test1: "Deutscher Testtext 1",
test2: "Deutscher Testtext 2"
},
en: {
test1: "English testtext 1",
test2: "English testtext 2"
},
};
*/
var locales = {
de: require('./locales/de.json'),
en: require('./locales/en.json')
};
Vue.use(VueI18n);
Vue.config.lang = 'de';
Object.keys(locales).forEach(function (lang) {
Vue.locale(lang, locales[lang])
});
...
Content of my en.json:
{
"test1": "English esttext 1",
"test2": "English testtext 2"
}
I found the solution by myself:
load your locales:
var locales = {
en: require('json!./locales/en.json),
// more languages
}
have fun
Thanks, your example helped me out! Note that if you鈥檙e using Webpack 2 or higher, the above syntax will work even without installing json-loader.
Hey, @Brotzka , thanks for the example. How about if you're fetching the JSON file from a url? For example:
``js
const baseUrl = 'https://fakeUrl.com';
const langData = async(base, lang) => {
const langContent = await fetch(${base}/${lang}.json`)
.then(res => res.json())
.catch(err => console.log(err));;
return langContent;
};
// Call the function for each object
export default new VueI18n({
locale,
messages: {
'en-US': {
content: langData(baseUrl, 'en-US'),
},
'zh-CN': {
content: langData(baseUrl, 'zh-CN'),
},
},
});
Hey, @Brotzka , thanks for the example. How about if you're fetching the JSON file from a url? For example:
const baseUrl = 'https://fakeUrl.com'; const langData = async(base, lang) => { const langContent = await fetch(`${base}/${lang}.json`) .then(res => res.json()) .catch(err => console.log(err));; return langContent; }; // Call the function for each object export default new VueI18n({ locale, messages: { 'en-US': { content: langData(baseUrl, 'en-US'), }, 'zh-CN': { content: langData(baseUrl, 'zh-CN'), }, }, });
this works but ;
vue-i18n.esm.js?a925:38 [vue-i18n] Value of key 'welcomeMsg' is not a string or function !
vue-i18n.esm.js?a925:38 [vue-i18n] Cannot translate the value of keypath 'welcomeMsg'. Use the value of keypath as default.
en.json
{
"welcomeMsg": "en"
}
Most helpful comment
Thanks, your example helped me out! Note that if you鈥檙e using Webpack 2 or higher, the above syntax will work even without installing
json-loader.