Vue 3使用vue-i18n分离多个json文件?

lf5gs5x2  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(273)

这是我的文件夹结构:

这是我在plugins/i18n.ts中的代码

import { createI18n } from 'vue-i18n'
import en from '@/locales/en.json'
import kh from '@/locales/kh.json'
import enRecruitment from '@/modules/recruitments/locales/en.json'
import khRecruitment from '@/modules/recruitments/locales/kh.json'

// Merge english locales json files
const enSources = [en, enRecruitment]
const enMessages = enSources.reduce((acc: any, source: any) => {
    for (const key in source) {
        acc[key] = { ...(acc[key] || {}), ...source[key] }
    }
    return acc
}, {})

// Merge khmer locales json files
const khSources = [kh, khRecruitment]
const khMessages = enSources.reduce((acc: any, source: any) => {
    for (const key in source) {
        acc[key] = { ...(acc[key] || {}), ...source[key] }
    }
    return acc
}, {})

// console.log({ enMessages: JSON.stringify(enMessages), khMessages })

const i18n = createI18n({
    legacy: false, // Use Composition API
    locale: 'en', // Default locale
    fallbackLocale: 'en', // Fallback locale if translation not available
    messages: {
        en: enMessages,
        kh: khMessages,
        // Add other language translations here
    },
})

export default i18n

我想合并locales/en.json和modules/locales/en.json & locales/kh.json和modules/locales/kh.json
如何解决这个问题?

axr492tv

axr492tv1#

import { createI18n } from 'vue-i18n'
import en from '@/locales/en.json'
import kh from '@/locales/kh.json'
import enRecruitment from '@/modules/recruitments/locales/en.json'
import khRecruitment from '@/modules/recruitments/locales/kh.json'

// Merge english locales json files
const enMessages = Object.assign(en, enRecruitment);

// Merge khmer locales json files
const khMessages = Object.assign(kh, khRecruitment);

const i18n = createI18n({
    legacy: false, // Use Composition API
    locale: 'en', // Default locale
    fallbackLocale: 'en', // Fallback locale if translation not available
    messages: {
        en: enMessages,
        kh: khMessages,
        // Add other language translations here
    },
})

export default i18n;

相关问题