Skip to content

Instantly share code, notes, and snippets.

@dasmikko
Created October 1, 2021 05:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dasmikko/aa28a4c42312b558a251ab4fc1049f0c to your computer and use it in GitHub Desktop.
Save dasmikko/aa28a4c42312b558a251ab4fc1049f0c to your computer and use it in GitHub Desktop.
Split a single vue-i18n langauge file multiple languages in a single object
/**
i18n.js
**/
let langs = {}
function setDeepValue(obj, path, value) {
let newPath = [...path]
const currentKey = newPath[0]
if (newPath.length > 1) {
if (!obj[currentKey]) obj[currentKey] = {}
newPath.shift() // Remove first item
setDeepValue(obj[currentKey], newPath, value)
} else {
obj[currentKey] = value
}
}
function stepObject(obj, currentPath) {
for (var key in obj) {
// Do the recursive
if (typeof obj[key] === "object") {
stepObject(obj[key], [...currentPath, key])
}
if (typeof obj[key] === "string") {
const language = key
const stringValue = obj[key]
if (!langs.hasOwnProperty(language)) {
langs[language] = {}
}
setDeepValue(langs[language], currentPath, stringValue)
}
}
}
export function splitLangJson (json) {
stepObject(json, [])
return langs
}
/**
end of i18n.js
**/
/**
Example of usage with vitejs
**/
// Import the splitLangJson methods
import { splitLangJson } from './utils/i18n.js'
// Import your big language file
import langs from './i18n/langs.json?raw'
// Use it in vue-i18n
const i18n = createI18n({
locale: 'da',
messages: splitLangJson(JSON.parse(langs)) // Call the splitLangJson method, with the JSON object
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment