How to set relevant tags in HTML head when using @nuxtjs/i18n
. Such as: <html lang="en-US">
, <link rel="alternate" href="https://your.com" hreflang="en">
.
Dependence version:
"@nuxtjs/i18n": "^9.5.3",
"nuxt": "^3.15.0",
nuxt.config.ts
, tips:
locales
must havecode
andlanguage
.baseUrl
, for generatealternate link
.
const appUrl = "https://your.com";
export default defineNuxtConfig({
i18n: {
locales: [
{
code: "en",
name: "English",
language: "en-US",
},
{
code: "zh",
name: "简体中文",
language: "zh-CN",
},
], // used in URL path prefix
defaultLocale: "en", // default locale of your project for Nuxt pages and routings
strategy: "prefix_except_default",
detectBrowserLanguage: false,
baseUrl: appUrl,
// https://github.com/nuxt-modules/i18n/issues/3238#issuecomment-2672492536
bundle: {
optimizeTranslationDirective: false,
},
},
});
i18n/i18n.config.ts
:
export default defineI18nConfig(() => ({
legacy: false, // to use Composition API. will be removed at vue-i18n v12 https://vue-i18n.intlify.dev/api/general.html#legacy
messages: {
zh: {
Home: "首页",
},
en: {
Home: "Home",
},
},
}));
Then you must have the following code, which is recommended to be placed in the layout component:
// seo for locale
const i18nHead = useLocaleHead();
useHead(() => ({
htmlAttrs: {
lang: i18nHead.value.htmlAttrs!.lang,
},
link: [...(i18nHead.value.link || [])],
meta: [...(i18nHead.value.meta || [])],
}));