diff --git a/src/module.ts b/src/module.ts index 7e9c3a21f..295905a0a 100644 --- a/src/module.ts +++ b/src/module.ts @@ -234,6 +234,7 @@ export default defineNuxtModule({ // for core plugin addPlugin(resolve(runtimeDir, 'plugins/i18n')) + addPlugin(resolve(runtimeDir, 'plugins/switch-locale-path-ssr')) // for composables nuxt.options.alias['#i18n'] = resolve(distDir, 'runtime/composables/index.mjs') diff --git a/src/runtime/plugins/i18n.ts b/src/runtime/plugins/i18n.ts index dcc80e995..18d968e2e 100644 --- a/src/runtime/plugins/i18n.ts +++ b/src/runtime/plugins/i18n.ts @@ -7,11 +7,9 @@ import { isSSG, localeLoaders, parallelPlugin, - normalizedLocales, - SWITCH_LOCALE_PATH_LINK_IDENTIFIER + normalizedLocales } from '#build/i18n.options.mjs' import { loadVueI18nOptions, loadInitialMessages, loadLocale } from '../messages' -import { useSwitchLocalePath } from '../composables' import { loadAndSetLocale, detectLocale, @@ -401,29 +399,6 @@ export default defineNuxtPlugin({ // inject for nuxt helpers injectNuxtHelpers(nuxtContext, i18n) - // Replace `SwitchLocalePathLink` href in rendered html for SSR support - if (runtimeI18n.experimental.switchLocalePathLinkSSR === true) { - const switchLocalePath = useSwitchLocalePath() - - const switchLocalePathLinkWrapperExpr = new RegExp( - [ - ``, - `.+?`, - `` - ].join(''), - 'g' - ) - - nuxt.hook('app:rendered', ctx => { - if (ctx.renderResult?.html == null) return - - ctx.renderResult.html = ctx.renderResult.html.replaceAll( - switchLocalePathLinkWrapperExpr, - (match: string, p1: string) => match.replace(/href="([^"]+)"/, `href="${switchLocalePath(p1 ?? '')}"`) - ) - }) - } - let routeChangeCount = 0 addRouteMiddleware( diff --git a/src/runtime/plugins/switch-locale-path-ssr.ts b/src/runtime/plugins/switch-locale-path-ssr.ts new file mode 100644 index 000000000..87d3911d2 --- /dev/null +++ b/src/runtime/plugins/switch-locale-path-ssr.ts @@ -0,0 +1,32 @@ +import { defineNuxtPlugin } from '#imports' +import { useSwitchLocalePath } from '#i18n' +import { SWITCH_LOCALE_PATH_LINK_IDENTIFIER } from '#build/i18n.options.mjs' + +// Replace `SwitchLocalePathLink` href in rendered html for SSR support +export default defineNuxtPlugin({ + name: 'i18n:plugin:switch-locale-path-ssr', + dependsOn: ['i18n:plugin'], + setup(nuxt) { + if (nuxt.$config.public.i18n.experimental.switchLocalePathLinkSSR !== true) return + + const switchLocalePath = useSwitchLocalePath() + + const switchLocalePathLinkWrapperExpr = new RegExp( + [ + ``, + `.+?`, + `` + ].join(''), + 'g' + ) + + nuxt.hook('app:rendered', ctx => { + if (ctx.renderResult?.html == null) return + + ctx.renderResult.html = ctx.renderResult.html.replaceAll( + switchLocalePathLinkWrapperExpr, + (match: string, p1: string) => match.replace(/href="([^"]+)"/, `href="${switchLocalePath(p1 ?? '')}"`) + ) + }) + } +})