跳轉到內容

国际化 ​

要使用内置的 i18n (国际化) 功能,需要建立類似于下面的目录结构:

docs/
├─ es/
│  ├─ foo.md
├─ fr/
│  ├─ foo.md
├─ foo.md

然後在 docs/.vitepress/config.ts 中:

docs/.vitepress/config.ts
ts
import { defineConfig } from 'vitepress'

export default defineConfig({
  // 共享属性和其他顶层内容...

  locales: {
    root: {
      label: 'English',
      lang: 'en'
    },
    fr: {
      label: 'French',
      lang: 'fr', // 可选,将作为 `lang` 属性新增到 `html` 标签中
      link: '/fr/guide' // 默认 /fr/ -- 显示在導航栏翻译選單上,可以是外部的

      // 其余 locale 特定属性...
    }
  }
})

下面的属性能够被每个 locale 覆盖 (包括 root):

ts
interface LocaleSpecificConfig<ThemeConfig = any> {
  lang?: string
  dir?: string
  title?: string
  titleTemplate?: string | boolean
  description?: string
  head?: HeadConfig[] // 将與现有的头部条目合并,重复的元标签将自动删除
  themeConfig?: ThemeConfig // 會进行浅层合并,常见内容可放在顶层的 themeConfig 属性中
}

有关自訂默认主題的文本占位符的信息,请參考 DefaultTheme.Config 介面。不要在 locale 级别覆盖 themeConfig.algolia 或 themeConfig.carbonAds。想获取多語言搜索的信息,请參考 Algolia 文件。

提示:配置文件也可以是 docs/.vitepress/config/index.ts。通過为每个语言环境建立一个配置文件,然後从 index.ts 合并并导出它们,可以更好地组织文件。

为本地化设置子目录 ​

下面是一个组织良好的结构:

docs/
├─ en/
│  ├─ foo.md
├─ es/
│  ├─ foo.md
├─ fr/
   ├─ foo.md

但是,VitePress 默认不會将 / 重定向到 /en/。需要配置服务器来实现这一点。例如,在使用 Netlify 时,可以新增一个 docs/public/_redirects 文件,如下所示:

/*  /es/:splat  302  Language=es
/*  /fr/:splat  302  Language=fr
/*  /en/:splat  302

提示: 如果使用上述的方法,可以使用 nf_lang cookie 来儲存用户的语言選擇。例如,可以在主題中新增以下程式碼:

docs/.vitepress/theme/index.ts
ts
import DefaultTheme from 'vitepress/theme'
import Layout from './Layout.vue'

export default {
  extends: DefaultTheme,
  Layout
}
docs/.vitepress/theme/Layout.vue
vue
<script setup lang="ts">
import DefaultTheme from 'vitepress/theme'
import { useData, inBrowser } from 'vitepress'
import { watchEffect } from 'vue'

const { lang } = useData()
watchEffect(() => {
  if (inBrowser) {
    document.cookie = `nf_lang=${lang.value}; expires=Mon, 1 Jan 2030 00:00:00 UTC; path=/`
  }
})
</script>

<template>
  <DefaultTheme.Layout />
</template>

RTL 支援 (实验性功能) ​

支援 RTL 需要在配置中指定 dir: 'rtl' 并且使用一些 RTLCSS PostCSS 外掛,例如 https://github.com/MohammadYounes/rtlcss, https://github.com/vkalinichev/postcss-rtl 或者 https://github.com/elchininet/postcss-rtlcss。需要配置 PostCSS 外掛,使用 :where([dir="ltr"]) 和 :where([dir="rtl"]) 作为前缀,以防止 CSS 特异性问题。

最後更新於:

基於 MIT 授權發布