跳到內容

國際化

若要使用內建的 i18n 功能,需要建立以下目錄結構

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

然後在 docs/.vitepress/config.ts

ts
import { defineConfig } from 'vitepress'

export default defineConfig({
  // shared properties and other top-level stuff...

  locales: {
    root: {
      label: 'English',
      lang: 'en'
    },
    fr: {
      label: 'French',
      lang: 'fr', // optional, will be added  as `lang` attribute on `html` tag
      link: '/fr/guide' // default /fr/ -- shows on navbar translations menu, can be external

      // other locale specific properties...
    }
  }
})

可以覆寫每個地區設定(包括根目錄)的下列屬性

ts
interface LocaleSpecificConfig<ThemeConfig = any> {
  lang?: string
  dir?: string
  title?: string
  titleTemplate?: string | boolean
  description?: string
  head?: HeadConfig[] // will be merged with existing head entries, duplicate meta tags are automatically removed
  themeConfig?: ThemeConfig // will be shallow merged, common stuff can be put in top-level themeConfig entry
}

參閱 DefaultTheme.Config 介面,以取得關於自訂預設佈景主題的提示文字的詳細資料。請勿在地區設定層級覆寫 themeConfig.algoliathemeConfig.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 來保留使用者的語言選擇

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

export default {
  extends: DefaultTheme,
  Layout
}
vue
<!-- docs/.vitepress/theme/Layout.vue -->
<script setup lang="ts">
import DefaultTheme from 'vitepress/theme'
import { useData } 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/rtlcsshttps://github.com/vkalinichev/postcss-rtlhttps://github.com/elchininet/postcss-rtlcss。你需要設定你的 PostCSS 外掛程式,以使用 :where([dir="ltr"]):where([dir="rtl"]) 作為前綴,以防止 CSS 特異性問題。

在 MIT 授權條款下釋出。