You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
vitepress/docs/zh/guide/i18n.md

3.3 KiB

国际化

你可以创建如下的目录结构来使你的站点国际化:

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

然后我们需要在 docs/.vitepress/config.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...
    }
  }
})

每个语言环境 (包括根目录) 都可以覆盖以下属性:

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.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 去存储用户的语言偏好。如下是一个非常基本的例子,在自定义主题的 setup 函数里面,你可以这样做:

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

export default {
  ...DefaultTheme,
  setup() {
    const { lang } = useData()
    watchEffect(() => {
      if (inBrowser) {
        document.cookie = `nf_lang=${lang.value}; expires=Mon, 1 Jan 2024 00:00:00 UTC; path=/`
      }
    })
  }
}

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 特有的问题。