From 173e3e0f27be5bd39fac0e7ae1c2ceca62089005 Mon Sep 17 00:00:00 2001 From: kazuya kawaguchi Date: Mon, 10 Oct 2022 10:27:57 +0900 Subject: [PATCH] feat: support extending messages hook (#1550) * feat: support extending messages hook * add e2e spec --- TODO.md | 2 +- docs/content/30.guide/13.extend-messages.md | 39 ++++++------- docs/content/50.API/7.nuxt.md | 40 +++++++++++++- playground/module1.ts | 20 +++++++ playground/nuxt.config.ts | 7 ++- playground/pages/index.vue | 1 + specs/extend_messages.spec.ts | 30 ++++++++++ specs/fixtures/basic/module.ts | 21 +++++++ specs/fixtures/basic/nuxt.config.ts | 3 +- specs/fixtures/basic/pages/index.vue | 3 + src/bundler.ts | 25 +++++---- src/gen.ts | 20 +++++++ src/messages.ts | 31 +++++++++++ src/module.ts | 23 ++++++-- src/options.d.ts | 2 + src/runtime/internal.ts | 61 ++++++++++++++------- src/runtime/plugin.ts | 6 +- src/runtime/utils.ts | 18 ++++++ test/__snapshots__/gen.test.ts.snap | 18 ++++++ test/gen.test.ts | 13 +++++ 20 files changed, 317 insertions(+), 66 deletions(-) create mode 100644 playground/module1.ts create mode 100644 specs/extend_messages.spec.ts create mode 100644 specs/fixtures/basic/module.ts create mode 100644 src/messages.ts diff --git a/TODO.md b/TODO.md index 3b73210cf..d443cafbf 100644 --- a/TODO.md +++ b/TODO.md @@ -33,7 +33,7 @@ This todo is based on [nuxt/i18n](https://i18n.nuxtjs.org/) docs. - [x] Different domains - [x] Locale fallback - [ ] Per-component translations -- [ ] Extending messages hook +- [x] Extending messages hook ## API Reference diff --git a/docs/content/30.guide/13.extend-messages.md b/docs/content/30.guide/13.extend-messages.md index b81119327..13d7ed9c1 100644 --- a/docs/content/30.guide/13.extend-messages.md +++ b/docs/content/30.guide/13.extend-messages.md @@ -3,11 +3,6 @@ title: Extending messages hook description: "Nuxt hook to extend app's messages" --- -::alert{type="warning"} -// TODO: -🚧 This feature is not implemented yet. -:: - If you're a **module author** and want that module to provide extra messages for your project, you can merge them into the normally loaded messages by using the `i18n:extend-messages` hook. To do this, in your module's setup file listen to the Nuxt hook and push your messages. `@nuxtjs/i18n` will do the rest. @@ -16,24 +11,26 @@ This is particularly useful if your module use translated content and you want t Example: -```js{}[my-module-exemple/setup.js] -export default function () { - const { nuxt } = this - - nuxt.hook('i18n:extend-messages', function (additionalMessages) { - additionalMessages.push({ - en: { - 'my-module-exemple': { - hello: 'Hello from external module' - } - }, - fr: { - 'my-module-exemple': { - hello: 'Bonjour depuis le module externe' +```ts{}[my-module-exemple/module1.ts] +import { defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + async setup(options, nuxt) { + nuxt.hook('i18n:extend-messages', (additionalMessages, localeCodes) => { + additionalMessages.push({ + en: { + 'my-module-exemple': { + hello: 'Hello from external module' + } + }, + fr: { + 'my-module-exemple': { + hello: 'Bonjour depuis le module externe' + } } - } + }) }) - }) + } } ``` diff --git a/docs/content/50.API/7.nuxt.md b/docs/content/50.API/7.nuxt.md index e25d09697..99bef2014 100644 --- a/docs/content/50.API/7.nuxt.md +++ b/docs/content/50.API/7.nuxt.md @@ -20,7 +20,7 @@ If you set `i18n.vueI18n.legacy` option to `false` in your `@nuxtjs/i18n` config Example use: -```js +```ts export default defineNuxtPlugin(nuxtApp => { nuxtApp.$i18n.onBeforeLanguageSwitch = (oldLocale, newLocale, isInitialSetup, nuxtApp) => { console.log('onBeforeLanguageSwitch', oldLocale, newLocale, isInitialSetup) @@ -35,3 +35,41 @@ export default defineNuxtPlugin(nuxtApp => { ### localeHead() See more info about those in [Extension of Vue](./vue) section. + + +## Extension of NuxtHooks + +### `i18n:extend-messages` Hook + +- **Arguments**: + - additionalMessages (type: ` LocaleMessages[]`) + - localeCodes (type: `string[]`) - locale codes, which is resolved with `locales` option + +The `additionalMessages` array can be pushed locale messages paired with the locale. + +Example: + +```ts +import { defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + async setup(options, nuxt) { + nuxt.hook('i18n:extend-messages', (additionalMessages, localeCodes) => { + additionalMessages.push({ + en: { + 'my-module-exemple': { + hello: 'Hello from external module' + } + }, + fr: { + 'my-module-exemple': { + hello: 'Bonjour depuis le module externe' + } + } + }) + }) + } +} +``` + +See also [Extending messages hook](../guide/extend-messages) \ No newline at end of file diff --git a/playground/module1.ts b/playground/module1.ts new file mode 100644 index 000000000..a65eb6632 --- /dev/null +++ b/playground/module1.ts @@ -0,0 +1,20 @@ +import { defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + async setup(options, nuxt) { + // @ts-ignore + await nuxt.hook('i18n:extend-messages', (messages, localeCodes) => { + messages.push({ + en: { + foo: 'Foo' + }, + fr: { + foo: 'Foo FR' + }, + ja: { + foo: 'Foo JA' + } + }) + }) + } +}) diff --git a/playground/nuxt.config.ts b/playground/nuxt.config.ts index a8b94b461..975156a3f 100644 --- a/playground/nuxt.config.ts +++ b/playground/nuxt.config.ts @@ -1,10 +1,11 @@ import { defineNuxtConfig } from 'nuxt' // @ts-ignore import I18nModule from '../dist/module.mjs' +import Module1 from './module1' // https://v3.nuxtjs.org/docs/directory-structure/nuxt.config export default defineNuxtConfig({ - modules: [I18nModule], + modules: [Module1, I18nModule], vite: { build: { @@ -45,10 +46,10 @@ export default defineNuxtConfig({ // strategy: 'no_prefix', // strategy: 'prefix', // strategy: 'prefix_and_default', - parsePages: false, + // parsePages: false, pages: { about: { - ja: false + ja: '/about-ja' } }, // differentDomains: true, diff --git a/playground/pages/index.vue b/playground/pages/index.vue index 5c2d6d618..118865e79 100644 --- a/playground/pages/index.vue +++ b/playground/pages/index.vue @@ -14,6 +14,7 @@ definePageMeta({ console.log('useBrowserLocale', useBrowserLocale()) console.log('localeProperties', localeProperties) +console.log('foo', t('foo')) function getLocaleName(code: string) { const locale = (locales.value as LocaleObject[]).find(i => i.code === code) diff --git a/specs/extend_messages.spec.ts b/specs/extend_messages.spec.ts new file mode 100644 index 000000000..d7831c653 --- /dev/null +++ b/specs/extend_messages.spec.ts @@ -0,0 +1,30 @@ +import { test, expect } from 'vitest' +import { fileURLToPath } from 'node:url' +import { setup, url, createPage } from '@nuxt/test-utils' +import { getText } from './helper' + +await setup({ + rootDir: fileURLToPath(new URL(`./fixtures/basic`, import.meta.url)), + browser: true, + // overrides + nuxtConfig: { + i18n: { + defaultLocale: 'en' + } + } +}) + +test('extend message hook', async () => { + const home = url('/') + const page = await createPage() + const messages: string[] = [] + page.on('console', msg => messages.push(msg.text())) + await page.goto(home) + + expect(await getText(page, '#extend-message')).toEqual('Hello from external module') + + // click `fr` lang switch link + await page.locator('#lang-switcher-with-nuxt-link a').click() + + expect(await getText(page, '#extend-message')).toEqual('Bonjour depuis le module externe') +}) diff --git a/specs/fixtures/basic/module.ts b/specs/fixtures/basic/module.ts new file mode 100644 index 000000000..d23172c50 --- /dev/null +++ b/specs/fixtures/basic/module.ts @@ -0,0 +1,21 @@ +import { defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + async setup(options, nuxt) { + // @ts-ignore + await nuxt.hook('i18n:extend-messages', (messages, localeCodes) => { + messages.push({ + en: { + 'my-module-exemple': { + hello: 'Hello from external module' + } + }, + fr: { + 'my-module-exemple': { + hello: 'Bonjour depuis le module externe' + } + } + }) + }) + } +}) diff --git a/specs/fixtures/basic/nuxt.config.ts b/specs/fixtures/basic/nuxt.config.ts index 8c3f6ff43..c0708fa76 100644 --- a/specs/fixtures/basic/nuxt.config.ts +++ b/specs/fixtures/basic/nuxt.config.ts @@ -1,9 +1,10 @@ import { defineNuxtConfig } from 'nuxt' import I18nModule from '../../..' +import CustomModule from './module' // https://v3.nuxtjs.org/docs/directory-structure/nuxt.config export default defineNuxtConfig({ - modules: [I18nModule], + modules: [CustomModule, I18nModule], i18n: { lazy: false, diff --git a/specs/fixtures/basic/pages/index.vue b/specs/fixtures/basic/pages/index.vue index eca8bc32c..4e5881c87 100644 --- a/specs/fixtures/basic/pages/index.vue +++ b/specs/fixtures/basic/pages/index.vue @@ -49,6 +49,9 @@ useHead({ >: {{ i18nHead }} +
+ {{ t('my-module-exemple.hello') }} +
{{ $t('about') }} {{ $t('blog') }} , nuxt: Nuxt, - hasLocaleFiles: boolean, - langPath: string | null + options: { + nuxtOptions: Required + hasLocaleFiles: boolean + langPath: string | null + } ) { + const { nuxtOptions, hasLocaleFiles, langPath } = options + // setup nitro if (nuxt.options.nitro.replace) { - nuxt.options.nitro.replace['__DEBUG__'] = options.debug + nuxt.options.nitro.replace['__DEBUG__'] = nuxtOptions.debug } else { nuxt.options.nitro.replace = { - __DEBUG__: options.debug + __DEBUG__: nuxtOptions.debug } } debug('nitro.replace', nuxt.options.nitro.replace) @@ -29,10 +33,7 @@ export async function extendBundler( // extract macros from components const macroOptions: TransformMacroPluginOptions = { dev: nuxt.options.dev, - sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client, - macros: { - defineI18nRoute: 'i18n' - } + sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client } try { @@ -58,7 +59,7 @@ export async function extendBundler( __VUE_I18N_FULL_INSTALL__: 'true', __VUE_I18N_LEGACY_API__: 'true', __INTLIFY_PROD_DEVTOOLS__: 'false', - __DEBUG__: JSON.stringify(options.debug) + __DEBUG__: JSON.stringify(nuxtOptions.debug) }) ) }) @@ -80,10 +81,10 @@ export async function extendBundler( extendViteConfig(config => { if (config.define) { - config.define['__DEBUG__'] = JSON.stringify(options.debug) + config.define['__DEBUG__'] = JSON.stringify(nuxtOptions.debug) } else { config.define = { - __DEBUG__: JSON.stringify(options.debug) + __DEBUG__: JSON.stringify(nuxtOptions.debug) } } debug('vite.config.define', config.define) diff --git a/src/gen.ts b/src/gen.ts index 58fad8a04..a0a259afa 100644 --- a/src/gen.ts +++ b/src/gen.ts @@ -5,6 +5,7 @@ import { genImport, genSafeVariableName, genDynamicImport } from 'knitwork' import type { NuxtI18nOptions, NuxtI18nInternalOptions, LocaleInfo } from './types' import type { NuxtI18nOptionsDefault } from './constants' +import type { AdditionalMessages } from './messages' export type LoaderOptions = { localeCodes?: string[] @@ -12,6 +13,7 @@ export type LoaderOptions = { nuxtI18nOptions?: NuxtI18nOptions nuxtI18nOptionsDefault?: NuxtI18nOptionsDefault nuxtI18nInternalOptions?: NuxtI18nInternalOptions + additionalMessages?: AdditionalMessages } const debug = createDebug('@nuxtjs/i18n:gen') @@ -93,6 +95,8 @@ export function generateLoaderOptions( } codes += `}\n` return codes + } else if (rootKey === 'additionalMessages') { + return `export const ${rootKey} = ${generaeteAdditionalMessages(rootValue, dev)}\n` } else { return `export const ${rootKey} = ${toCode(rootValue)}\n` } @@ -122,6 +126,22 @@ function generateVueI18nOptions(options: Record, dev: boolean): str return genCode } +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function generaeteAdditionalMessages(value: Record, dev: boolean): string { + let genCode = 'Object({' + for (const [locale, messages] of Object.entries(value)) { + genCode += `${JSON.stringify(locale)}:[` + for (const [, p] of Object.entries(messages)) { + genCode += `() => Promise.resolve(${ + generateJSON(JSON.stringify(p), { type: 'bare', env: dev ? 'development' : 'production' }).code + }),` + } + genCode += `],` + } + genCode += '})' + return genCode +} + // eslint-disable-next-line @typescript-eslint/no-explicit-any export function stringifyObj(obj: Record): string { return `Object({${Object.entries(obj) diff --git a/src/messages.ts b/src/messages.ts new file mode 100644 index 000000000..237a38b4e --- /dev/null +++ b/src/messages.ts @@ -0,0 +1,31 @@ +import createDebug from 'debug' + +import type { Nuxt } from '@nuxt/schema' +import type { DefineLocaleMessage, Locale, LocaleMessages } from 'vue-i18n' + +const debug = createDebug('@nuxtjs/i18n:messages') + +export type AdditionalMessages = Record + +export async function extendMessages(nuxt: Nuxt, localeCodes: string[]): Promise { + const additionalMessages: LocaleMessages[] = [] + await nuxt.callHook('i18n:extend-messages', additionalMessages, localeCodes) + debug('i18n:extend-messages additional messages', additionalMessages) + + return normalizeAdditionalMessages(additionalMessages, localeCodes) +} + +async function normalizeAdditionalMessages(additional: LocaleMessages[], localeCodes: string[]) { + const additionalMessages: AdditionalMessages = {} + for (const localeCode of localeCodes) { + additionalMessages[localeCode] = [] + } + + for (const [, messages] of Object.entries(additional)) { + for (const [locale, message] of Object.entries(messages)) { + additionalMessages[locale].push(message) + } + } + + return additionalMessages +} diff --git a/src/module.ts b/src/module.ts index b8ff872b0..295e1d528 100644 --- a/src/module.ts +++ b/src/module.ts @@ -3,15 +3,17 @@ import { isObject, isString } from '@intlify/shared' import { defineNuxtModule, isNuxt2, isNuxt3, getNuxtVersion, addPlugin, addTemplate, addImports } from '@nuxt/kit' import { resolve } from 'pathe' import defu from 'defu' -import { extendBundler } from './bundler' import { setupAlias } from './alias' -import { NUXT_I18N_MODULE_ID, DEFAULT_OPTIONS } from './constants' -import { formatMessage, getNormalizedLocales, resolveLocales } from './utils' import { setupPages } from './pages' +import { extendMessages } from './messages' +import { extendBundler } from './bundler' import { generateLoaderOptions } from './gen' +import { NUXT_I18N_MODULE_ID, DEFAULT_OPTIONS } from './constants' +import { formatMessage, getNormalizedLocales, resolveLocales } from './utils' import { distDir, runtimeDir } from './dirs' import type { NuxtI18nOptions } from './types' +import type { DefineLocaleMessage, LocaleMessages } from 'vue-i18n' export * from './types' @@ -21,7 +23,6 @@ export default defineNuxtModule({ meta: { name: NUXT_I18N_MODULE_ID, configKey: 'i18n' - // TODO: // compatibility: { // nuxt: '^3.0.0', // bridge: false @@ -75,6 +76,9 @@ export default defineNuxtModule({ ? resolve(nuxt.options.rootDir, options.vueI18n) : {} + // extend messages via 3rd party nuxt modules + const additionalMessages = await extendMessages(nuxt, localeCodes) + // setup nuxt/pages if (options.strategy !== 'no_prefix' && localeCodes.length) { await setupPages(options, nuxt, { isBridge: isNuxt2(nuxt), localeCodes }) @@ -118,6 +122,7 @@ export default defineNuxtModule({ { localeCodes, localeInfo, + additionalMessages, nuxtI18nOptions: options, nuxtI18nOptionsDefault: DEFAULT_OPTIONS, nuxtI18nInternalOptions: { @@ -130,7 +135,11 @@ export default defineNuxtModule({ }) // extend bundler - await extendBundler(options, nuxt, hasLocaleFiles, langPath) + await extendBundler(nuxt, { + nuxtOptions: options as Required, + hasLocaleFiles, + langPath + }) // auto imports await addImports([ @@ -190,4 +199,8 @@ declare module '@nuxt/schema' { interface NuxtConfig { i18n?: NuxtI18nOptions } + + interface NuxtHooks { + 'i18n:extend-messages': (messages: LocaleMessages[], localeCodes: string[]) => Promise + } } diff --git a/src/options.d.ts b/src/options.d.ts index e486ede3a..57b5b3bef 100644 --- a/src/options.d.ts +++ b/src/options.d.ts @@ -11,6 +11,8 @@ export const loadMessages: () => Promise = () => Promise.resolve({}) // eslint-disable-next-line @typescript-eslint/no-explicit-any export const localeMessages: Record Promise> = {} // eslint-disable-next-line @typescript-eslint/no-explicit-any +export const additionalMessages: Record Promise>> = {} +// eslint-disable-next-line @typescript-eslint/no-explicit-any export const resolveNuxtI18nOptions: ( context: Context ) => Promise>> = () => Promise.resolve({}) diff --git a/src/runtime/internal.ts b/src/runtime/internal.ts index e0ac6e257..2f6e6fbcf 100644 --- a/src/runtime/internal.ts +++ b/src/runtime/internal.ts @@ -15,7 +15,7 @@ import { parse, serialize } from 'cookie-es' import { hasProtocol } from 'ufo' import isHTTPS from 'is-https' import { useRequestHeaders, useRequestEvent } from '#imports' -import { nuxtI18nOptionsDefault, localeMessages } from '#build/i18n.options.mjs' +import { nuxtI18nOptionsDefault, localeMessages, additionalMessages } from '#build/i18n.options.mjs' import type { NuxtApp } from '#imports' import type { I18nOptions, Locale, VueI18n, LocaleMessages, DefineLocaleMessage } from '@intlify/vue-i18n-bridge' @@ -98,24 +98,19 @@ export function parseAcceptLanguage(input: string): string[] { return input.split(',').map(tag => tag.split(';')[0]) } -async function loadMessage(context: NuxtApp, locale: Locale) { +async function loadMessage(context: NuxtApp, loader: () => Promise) { let message: LocaleMessages | null = null - const loader = localeMessages[locale] - if (loader) { - try { - const getter = await loader().then(r => r.default || r) - // TODO: support for js, cjs, mjs - if (isFunction(getter)) { - console.error(formatMessage('Not support executable file (e.g. js, cjs, mjs)')) - } else { - message = getter - } - } catch (e: any) { - // eslint-disable-next-line no-console - console.error(formatMessage('Failed locale loading: ' + e.message)) + try { + const getter = await loader().then(r => r.default || r) + // TODO: support for js, cjs, mjs + if (isFunction(getter)) { + console.error(formatMessage('Not support executable file (e.g. js, cjs, mjs)')) + } else { + message = getter } - } else { - console.warn(formatMessage('Could not find ' + locale + ' locale')) + } catch (e: any) { + // eslint-disable-next-line no-console + console.error(formatMessage('Failed locale loading: ' + e.message)) } return message } @@ -128,10 +123,34 @@ export async function loadLocale( setter: (locale: Locale, message: LocaleMessages) => void ) { if (process.server || process.dev || !loadedLocales.includes(locale)) { - const message = await loadMessage(context, locale) - if (message != null) { - setter(locale, message) - loadedLocales.push(locale) + const loader = localeMessages[locale] + if (loader != null) { + const message = await loadMessage(context, loader) + if (message != null) { + setter(locale, message) + loadedLocales.push(locale) + } + } else { + console.warn(formatMessage('Could not find ' + locale + ' locale in localeMessages')) + } + } +} + +const loadedAdditionalLocales: Locale[] = [] + +export async function loadAdditionalLocale( + context: NuxtApp, + locale: Locale, + merger: (locale: Locale, message: LocaleMessages) => void +) { + if (process.server || process.dev || !loadedAdditionalLocales.includes(locale)) { + const additionalLoaders = additionalMessages[locale] || [] + for (const additionalLoader of additionalLoaders) { + const message = await loadMessage(context, additionalLoader) + if (message != null) { + merger(locale, message) + loadedAdditionalLocales.push(locale) + } } } } diff --git a/src/runtime/plugin.ts b/src/runtime/plugin.ts index 833b7bd8e..1b795171a 100644 --- a/src/runtime/plugin.ts +++ b/src/runtime/plugin.ts @@ -17,6 +17,7 @@ import { localeCodes, resolveNuxtI18nOptions, nuxtI18nInternalOptions } from '#b import { loadInitialMessages, loadAndSetLocale, + mergeAddtionalMessages, detectLocale, detectRedirect, navigate, @@ -103,7 +104,7 @@ export default defineNuxtPlugin(async nuxt => { /** * NOTE: - * If `initLocale` is not set, then the `vueI18n` option `locale` is respect! + * If `initialLocale` is not set, then the `vueI18n` option `locale` is respect! * It means a mode that works only with simple vue-i18n, without nuxtjs/i18n routing, browser detection, SEO, and other features. */ initialLocale = initialLocale || vueI18nOptions.locale || 'en-US' @@ -323,6 +324,9 @@ export default defineNuxtPlugin(async nuxt => { // inject for nuxt helpers inejctNuxtHelpers(nuxtContext, i18n) + // merge addtional locale messages + await mergeAddtionalMessages(nuxtContext, i18n, initialLocale) + addRouteMiddleware( 'locale-changing', // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/src/runtime/utils.ts b/src/runtime/utils.ts index 5c85852b7..f6561d0c5 100644 --- a/src/runtime/utils.ts +++ b/src/runtime/utils.ts @@ -23,6 +23,7 @@ import { callVueI18nInterfaces, getVueI18nPropertyValue, loadLocale, + loadAdditionalLocale, defineGetter, getLocaleDomain, getDomainFromLocale, @@ -50,6 +51,10 @@ export function setLocaleMessage(i18n: I18n, locale: Locale, messages: Record) { + return callVueI18nInterfaces(i18n, 'mergeLocaleMessage', locale, messages) +} + function onBeforeLanguageSwitch( i18n: I18n, oldLocale: string, @@ -107,6 +112,16 @@ export async function loadInitialMessages( return messages } +export async function mergeAddtionalMessages( + context: Context, + i18n: I18n, + locale: Locale +) { + await loadAdditionalLocale(context, locale, (locale: Locale, message: Record) => + mergeLocaleMessage(i18n, locale, message) + ) +} + export async function loadAndSetLocale( newLocale: string, context: Context, @@ -161,6 +176,9 @@ export async function loadAndSetLocale( } } + // merge additional locale messages + await mergeAddtionalMessages(context, i18n, newLocale) + if (skipSettingLocaleOnNavigate) { return [ret, oldLocale] } diff --git a/test/__snapshots__/gen.test.ts.snap b/test/__snapshots__/gen.test.ts.snap index e859d1bfa..f2e8718d4 100644 --- a/test/__snapshots__/gen.test.ts.snap +++ b/test/__snapshots__/gen.test.ts.snap @@ -10,6 +10,8 @@ export const localeMessages = { \\"ja\\": () => Promise.resolve(locale_ja), } +export const additionalMessages = Object({}) + export const resolveNuxtI18nOptions = async (context) => { const nuxtI18nOptions = Object({}) nuxtI18nOptions.defaultLocale = \\"en\\" @@ -35,6 +37,8 @@ export const localeMessages = { \\"ja\\": () => import(\\"./locales/ja.json\\" /* webpackChunkName: \\"lang-ja\\" */), } +export const additionalMessages = Object({}) + export const resolveNuxtI18nOptions = async (context) => { const nuxtI18nOptions = Object({}) nuxtI18nOptions.defaultLocale = \\"en\\" @@ -59,6 +63,20 @@ export const localeMessages = { \\"ja\\": () => Promise.resolve(locale_ja), } +export const additionalMessages = Object({\\"en\\":[() => Promise.resolve({ + \\"foo\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"foo\\"])};fn.source=\\"foo\\";return fn;})(), + \\"hello\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"hello1\\"])};fn.source=\\"hello1\\";return fn;})() +}),() => Promise.resolve({ + \\"bar\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"bar\\"])};fn.source=\\"bar\\";return fn;})(), + \\"hello\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"hello2\\"])};fn.source=\\"hello2\\";return fn;})() +}),],\\"ja\\":[() => Promise.resolve({ + \\"buz\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"buz\\"])};fn.source=\\"buz\\";return fn;})(), + \\"hello\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"hello3\\"])};fn.source=\\"hello3\\";return fn;})() +}),() => Promise.resolve({ + \\"baz\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"baz\\"])};fn.source=\\"baz\\";return fn;})(), + \\"hello\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"hello4\\"])};fn.source=\\"hello4\\";return fn;})() +}),],}) + export const resolveNuxtI18nOptions = async (context) => { const nuxtI18nOptions = Object({}) const vueI18nOptionsLoader = async (context) => import(\\"~/plugins/vue-i18n.js\\").then(r => (r.default || r)(context)) diff --git a/test/gen.test.ts b/test/gen.test.ts index 70d6a7128..8885d8521 100644 --- a/test/gen.test.ts +++ b/test/gen.test.ts @@ -16,6 +16,16 @@ const LOCALE_INFO = [ path: './locales/ja.json' } ] +const ADDITIONAL_MESSAGES = { + en: [ + { foo: 'foo', hello: 'hello1' }, + { bar: 'bar', hello: 'hello2' } + ], + ja: [ + { buz: 'buz', hello: 'hello3' }, + { baz: 'baz', hello: 'hello4' } + ] +} const NUXT_I18N_OPTIONS = { defaultLocale: 'en', vueI18n: { @@ -53,6 +63,7 @@ it('basic', () => { const code = generateLoaderOptions(false, '/path/to/locales', { localeCodes: LOCALE_CODES, localeInfo: LOCALE_INFO, + additionalMessages: {}, nuxtI18nOptions: NUXT_I18N_OPTIONS, nuxtI18nOptionsDefault: DEFAULT_OPTIONS, nuxtI18nInternalOptions: NUXT_I18N_INTERNAL_OPTIONS @@ -65,6 +76,7 @@ it('lazy', () => { const code = generateLoaderOptions(true, '/path/to/locales', { localeCodes: LOCALE_CODES, localeInfo: LOCALE_INFO, + additionalMessages: {}, nuxtI18nOptions: NUXT_I18N_OPTIONS, nuxtI18nInternalOptions: NUXT_I18N_INTERNAL_OPTIONS }) @@ -76,6 +88,7 @@ it('vueI18n: path', () => { const code = generateLoaderOptions(false, '/path/to/locales', { localeCodes: LOCALE_CODES, localeInfo: LOCALE_INFO, + additionalMessages: ADDITIONAL_MESSAGES, nuxtI18nOptions: { vueI18n: '~/plugins/vue-i18n.js' },