i18n - 教程
This tutorial will walk you through the basics of the Docusaurus i18n system.
We will add French translations to a newly initialized English Docusaurus website.
Initialize a new site with npx create-docusaurus@latest website classic
(like this one).
Configure your site
Modify docusaurus.config.js
to add the i18n support for the French language.
Site configuration
Use the site i18n configuration to declare the i18n locales:
export default {
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr', 'fa'],
localeConfigs: {
en: {
htmlLang: 'en-GB',
},
// You can omit a locale (e.g. fr) if you don't need to override the defaults
fa: {
direction: 'rtl',
},
},
},
};
语言名称会被用于翻译文件的位置以及你的本地化网站的 base URL。 构建所有语言时,只有默认语言才会在 base URL 中省略它的名字。
Docusaurus uses the locale names to provide sensible defaults: the <html lang="...">
attribute, locale label, calendar format, etc. You can customize these defaults with the localeConfigs
.
Theme configuration
Add a navbar item of type localeDropdown
so that users can select the locale they want:
export default {
themeConfig: {
navbar: {
items: [
{
type: 'localeDropdown',
position: 'left',
},
],
},
},
};
You can pass a query parameter that will be appended to the URL when a user changes the locale using the dropdown (e.g. queryString: '?persistLocale=true'
).
This is useful for implementing an automatic locale detection on your server. For example, you can use this parameter to store the user's preferred locale in a cookie.
Start your site
Start your localized site in dev mode, using the locale of your choice:
- npm
- Yarn
- pnpm
npm run start -- --locale zh-Hans
yarn run start --locale zh-Hans
pnpm run start -- --locale zh-Hans
Your site is accessible at http://localhost:3000/fr/
.
We haven't provided any translation yet, so the site is mostly untranslated.
Docusaurus provides default translations for generic theme labels, such as "Next" and "Previous" for the pagination.
Please help us complete those default translations.
Each locale is a distinct standalone single-page application: it is not possible to start the Docusaurus sites in all locales at the same time.
Translate your site
All translation data for the French locale is stored in website/i18n/fr
. Each plugin sources its own translated content under the corresponding folder, while the code.json
file defines all text labels used in the React code.
After copying files around, restart your site with npm run start -- --locale fr
. Hot-reload will work better when editing existing files.
Translate your React code
For any React code you've written yourself: React pages, React components, etc., you will use the translation APIs.
Locate all text labels in your React code that will be visible to your users, and mark them with the translation APIs. There are two kinds of APIs:
- The
<Translate>
component wraps a string as a JSX element; - The
translate()
callback takes a message and returns a string.