使用@nuxtjs/i18n时,如何设置 HTML head 里的相关标签。如<html lang="en-US">, <link rel="alternate" href="https://your.com" hreflang="en">

依赖版本:

"@nuxtjs/i18n": "^9.5.3",
"nuxt": "^3.15.0",

nuxt.config.ts,重点有:

  • locales必须有codelanguage
  • baseUrl,用于生成alternate 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",
    },
  },
}));

然后必须要有下面代码,推荐放在布局组件(layout)里面:

// seo for locale
const i18nHead = useLocaleHead();
useHead(() => ({
  htmlAttrs: {
    lang: i18nHead.value.htmlAttrs!.lang,
  },
  link: [...(i18nHead.value.link || [])],
  meta: [...(i18nHead.value.meta || [])],
}));