diff --git a/src/index.js b/src/index.js index 6ff946c6d..d2f450daf 100644 --- a/src/index.js +++ b/src/index.js @@ -35,6 +35,29 @@ module.exports = function (userOptions) { return } + let defaultLangFile + + // Copy lang files to the build directory. + if (options.langDir) { + if (!options.locales.length || typeof options.locales[0] === 'string') { + console.warn('[' + options.MODULE_NAME + '] When using "langDir" option, the "locales" option must be a list of objects') + } + + const uniqueFiles = new Set(options.locales.map(locale => locale.file)) + + if (options.defaultLocale) { + defaultLangFile = options.locales.find(locale => locale.code === options.defaultLocale).file + } + + for (const file of uniqueFiles) { + const isUsingDefaultLangFile = file === defaultLangFile + this.addTemplate({ + src: resolve(this.options.srcDir, options.langDir, file), + fileName: join(ROOT_DIR, (isUsingDefaultLangFile ? 'default-lang' : 'langs'), file) + }) + } + } + const localeCodes = getLocaleCodes(options.locales) const { trailingSlash } = this.options.router @@ -48,6 +71,7 @@ module.exports = function (userOptions) { LOCALE_FILE_KEY, STRATEGIES, COMPONENT_OPTIONS_KEY, + defaultLangFile, localeCodes, trailingSlash } diff --git a/src/templates/utils.js b/src/templates/utils.js index 97cb8e021..6670fde60 100755 --- a/src/templates/utils.js +++ b/src/templates/utils.js @@ -1,8 +1,12 @@ import { LOCALE_CODE_KEY, LOCALE_FILE_KEY, - MODULE_NAME + MODULE_NAME, + defaultLangFile } from './options' +/* <% if (options.defaultLangFile) { %> */ +import defaultLangModule from './default-lang/<%= options.defaultLangFile %>' +/* <% } %> */ /** * Asynchronously load messages from translation files @@ -17,15 +21,20 @@ export async function loadLanguageAsync (context, locale) { } if (!app.i18n.loadedLanguages.includes(locale)) { - const langOptions = app.i18n.locales.find(l => l[LOCALE_CODE_KEY] === locale) - if (langOptions) { - const file = langOptions[LOCALE_FILE_KEY] + const localeObject = app.i18n.locales.find(l => l[LOCALE_CODE_KEY] === locale) + if (localeObject) { + const file = localeObject[LOCALE_FILE_KEY] if (file) { // Hiding template directives from eslint so that parsing doesn't break. /* <% if (options.langDir) { %> */ try { - const module = await import(/* webpackChunkName: "lang-[request]" */ '~/<%= options.langDir %>' + file) - const messages = module.default ? module.default : module + let langFileModule + if (file === defaultLangFile) { + langFileModule = defaultLangModule + } else { + langFileModule = await import(/* webpackChunkName: "lang-[request]" */ `./langs/${file}`) + } + const messages = langFileModule.default || langFileModule const result = typeof messages === 'function' ? await Promise.resolve(messages(context, locale)) : messages app.i18n.setLocaleMessage(locale, result) app.i18n.loadedLanguages.push(locale)