Translations & Localization
Docusaurus permet une fonctionnalité de traduction utile en utilisant Crowdin. Les fichiers de documentation écrits en anglais sont envoyés à Crowdin pour une traduction par les utilisateurs au sein d’une communauté. Les pages de haut niveau écrites avec des chaînes anglaises peuvent être traduites en enregistrant toutes les chaînes que vous souhaitez traduire dans une balise <translate> . D'autres titres et étiquettes seront également trouvés et correctement traduits.
Configurations de traduction de Docusaurus
Pour générer des fichiers d'exemple pour les traductions avec Docusaurus, exécutez le script examples avec l'argument de la ligne de commande translations :
npm run examples translations
ou
yarn examples translations
Ceci créera les fichiers suivants :
pages/en/help-with-translations.js
languages.js
../crowdin.yaml
- Le fichier pages/en/help-with-translations.jsinclut la même page d'aide de démarrage générée par le scriptexamplesmais inclut maintenant les balises de traduction.
Généralement, vous utiliserez
help-with-translations.jscomme guide pour activer les traductions dans vos autres pages, mais vous ne livrerez pas réellement le fichier à votre dépôt (c'est-à-dire que vous pourrez le supprimer). Cependant, si vous voulez une page d'Aide, et que vous n'en avez pas, vous pouvez renommer ce fichier enhelp.jset l'utiliser comme point de départ.
- Le fichier - languages.jsindique à Docusaurus quelles langues vous souhaitez activer pour votre site. Par défaut, nous espérons que l'anglais sera activé.
- Le fichier - crowdin.yamlest utilisé pour configurer l'intégration de Crowdin et est copié d'un niveau vers le haut dans le dépôt de votre projet Docusaurus. Si votre projet Docusaurus réside dans- /project/website, alors- crowdin.yamlsera copié dans- /project/crowdin.yaml.
Traduire vos docs existantes
Vos fichiers de documentation (par exemple les fichiers .md qui vivent dans votre répertoire docs) ne doivent pas être modifiés ou déplacés pour supporter les traductions. Ils seront envoyés à Crowdin pour être traduits directement.
Activer les traductions sur les pages
Les pages vous permettent de personnaliser la mise en page et le contenu spécifique des pages comme une page d'index personnalisée ou une page d'aide.
Les pages avec du texte que vous souhaitez traduire doivent être placées dans le répertoire site/pages/en .
Wrap strings that you want translated in a <translate> tag, and add the following require statement to the top of the file:
...
const translate = require('../../server/translate.js').translate;
...
<h2>
  <translate>This header will be translated</translate>
</h2>
...
Vous pouvez également inclure un attribut de description facultatif pour donner plus de contexte à un traducteur sur la façon de traduire la chaîne :
<p>
  <translate desc="flower, not verb">Rose</translate>
<p>
La balise
<translate>fonctionne généralement bien sur des chaînes de caractères pures. Si vous avez une chaîne comme "Docusaurus fournit actuellement un support pour aider votre site à utiliser translations", encapsuler la balise<translation>autour de cette chaîne entière causera des problèmes à cause du lien markdown, etc. Vos possibilités sont de ne pas traduire ces chaînes de caractères, ou de disséminer un tas de balises<translate>parmi les chaînes de caractères pures de cette chaîne.
Collecter des chaînes à traduire
Les chaînes dans les pages à traduire doivent être extraites et fournies à Crowdin.
Ajoutez le script suivant à votre fichier website/package.json s'il n'existe pas déjà :
{
  ...
  "scripts": {
    "write-translations": "docusaurus-write-translations"
  },
  ...
}
L'exécution du script générera un fichier website/i18n/fr.json contenant toutes les chaînes qui seront traduites de l'anglais dans d'autres langues.
Le script comprendra du texte provenant des endroits suivants :
- Les chaînes titleetsidebar_labeldans les entêtes du document markdown
- Les noms des catégories dans sidebars.json
- tagline dans siteConfig.js
- Les chaînes labelde headerLinks danssiteConfig.js
- Les chaînes enveloppées dans la balise <translate>dans tous les fichiers.jsdanspages
Chaînes de traduction personnalisées
Si vous voulez ajouter des chaînes de traduction personnalisées supplémentaires ou remplacer l'une des chaînes qui sont produites par le script qui crée le fichier website/i18n/en.json, vous pouvez ajouter un fichier website/data/custom-translation-strings.json . Le fichier doit être sous la forme :
{
  "localized-strings": {
    "docs": {
      "id": {
        "title": "string1",
        "sidebar_label": "string2"
      },
      "version-0.0.1-id": {
        "title": "string3",
        "sidebar_label": "string4"
      }
    }
  },
  "pages-strings": {
    "id3": "string3",
    "id4": "string4"
  }
}
où localized-strings représentent des chaînes de caractères dans le contenu de votre documentation et pages-strings représente des métadonnées dans votre documentation (par exemple, titre, liens, etc.).
Voici un exemple :
{
  "_comment": "Ce fichier est utilisé pour fournir des chaînes personnalisées pour les traductions, y compris en supportant les valeurs par défaut",
  "localized-strings": {
    "traduction": "Traductions et localisation"
  },
  "pages-strings": {
    "Aidez à traduire|recrutez des traducteurs de la communauté pour votre projet": "Aidez-nous à traduire"
  }
}
Voir le website/i18n/en.json généré pour exemple.
Comment les chaînes de caractères sont traduites
Docusaurus lui-même ne fait aucune traduction d'une langue à une autre. Instead, it integrates Crowdin to upload translations and then download the appropriately translated files from Crowdin.
Comment Docusaurus utilise les traductions de chaînes de caractères
This section provides context about how translations in Docusaurus works.
Strings
A Docusaurus site has many strings used throughout it that require localization. However, maintaining a list of strings used throughout a site can be laborious. Docusaurus simplifies this by centralizing strings.
The header navigation, for example, can have links to 'Home' or your 'Blog'. This and other strings found in the headers and sidebars of pages are extracted and placed into i18n/en.json. When your files are translated, say into Spanish, an i18n/es-ES.json file will be downloaded from Crowdin. Then, when the Spanish pages are generated, Docusaurus will replace the English version of corresponding strings with translated strings from the corresponding localized strings file (e.g. In a Spanish enabled site 'Help' will become 'Ayuda').
Markdown Files
For documentation files themselves, translated versions of these files are downloaded and then rendered through the proper layout template.
Other Pages
For other pages, Docusaurus will automatically transform all <translate> tags it finds into function calls that return the translated strings from the corresponding localized file locale.json.
Crowdin
Crowdin is a company that provides translation services. For Open Source projects, Crowdin provides free string translations.
Create your translation project on Crowdin. You can use Crowdin's guides to learn more about the translations workflow. We suggest that you deselect and do not include "English" as a translatable language to prevent the creation of en-US localization files as this can lead to confusion.
Ensure in your Crowdin settings, in the Translations section, that "Duplicate Strings" are set to "Hide - all duplicates will share the same translation". This setting will ensure that identical strings between versions share a single translation.
Your project will need a crowdin.yaml file generated. If you ran yarn examples translations or npm run examples translations, this file was created for you on the same level as your website directory.
You will need to install the
crowdincommand line interface. Please follow the installation directions.
The example below can be automatically generated by the Docusaurus cli with the examples script. It should be placed in the top level of your project directory to configure how and what files are uploaded/downloaded.
Below is an example Crowdin configuration for the respective languages: German, Spanish, French, Japanese, Korean, Bahasa Indonesia, Portuguese Brazilian, Chinese Simplified, and Chinese Traditional.
project_identifier_env: CROWDIN_DOCUSAURUS_PROJECT_ID
api_key_env: CROWDIN_DOCUSAURUS_API_KEY
base_path: './'
preserve_hierarchy: true
files:
  - source: '/docs/**/*.md'
    translation: '/website/translated_docs/%locale%/**/%original_file_name%'
    languages_mapping: &anchor
      locale:
        'de': 'de'
        'es-ES': 'es-ES'
        'fr': 'fr'
        'ja': 'ja'
        'ko': 'ko'
        'mr': 'mr-IN'
        'pt-BR': 'pt-BR'
        'zh-CN': 'zh-CN'
        'zh-TW': 'zh-TW'
You can go here to learn more about customizing your crowdin.yaml file.
Setup the Crowdin Scripts
You will want to manually sync your files to and from Crowdin. The sync process will upload any markdown files in /docs as well as translatable strings in website/i18n/en.json. (These strings can be generated by running yarn write-translations.)
You can add the following to your package.json to manually trigger Crowdin.
"scripts": {
  "crowdin-upload": "crowdin --config ../crowdin.yaml upload sources --auto-update -b master",
  "crowdin-download": "crowdin --config ../crowdin.yaml download -b master"
},
Manual File Sync
You will always want to upload your markdown files and translatable strings first and download the translations section. So run the commands in this order:
CROWDIN_DOCUSAURUS_PROJECT_ID=YOUR_CROWDIN_PROJECT_ID CROWDIN_DOCUSAURUS_API_KEY=YOUR_CROWDIN_API_KEY yarn run crowdin-upload
CROWDIN_DOCUSAURUS_PROJECT_ID=YOUR_CROWDIN_PROJECT_ID CROWDIN_DOCUSAURUS_API_KEY=YOUR_CROWDIN_API_KEY yarn run crowdin-download
YOUR_CROWDIN_PROJECT_IDis the name of your Crowdin project. e.g., for https://crowdin.com/project/docusaurus/, that variable would be set todocusaurus.YOUR_CROWDIN_API_KEYis a unique key that is like a password. You can find it in theAPItab of your Crowdin project'sSettings.
These commands require having an environment variable set with your Crowdin project id and api key (
CROWDIN_PROJECT_ID,CROWDIN_API_KEY). You can preface them inline as done above or add them permanently to your.bashrcor.bash_profile.
If you run more than one localized Docusaurus project on your computer, you should change the name of the environment variables to something unique (
CROWDIN_PROJECTNAME_PROJECT_ID,CROWDIN_PROJECTNAME_API_KEY).
Since the files are generated, you do not need to have any files in your
website/i18norwebsite/translated_docsdirectory as part of your repo. So you can can addwebsite/i18n/*andwebsite/translated_docsto your.gitignorefile.
Automated File Sync Using CircleCI
You can automate pulling down and uploading translations for your files using the CircleCI web continuous integration service.
First, update the .circleci/config.yml file in your project directory to include steps to upload English files to be translated and download translated files using the Crowdin CLI. Here is an example .circleci/config.yml file:
# If you only want circle to run on direct commits to master, you can uncomment this out
# and uncomment the filters: *filter-only-master down below too
#
# aliases:
#  - &filter-only-master
#    branches:
#      only:
#        - master
version: 2
jobs:
  deploy-website:
    docker:
      # specify the version you desire here
      - image: circleci/node:8.11.1
    steps:
      - checkout
      - run:
          name: Deploying to GitHub Pages
          command: |
            git config --global user.email "<GITHUB_USERNAME>@users.noreply.github.com"
            git config --global user.name "<YOUR_NAME>"
            echo "machine github.com login <GITHUB_USERNAME> password $GITHUB_TOKEN" > ~/.netrc
            # install Docusaurus and generate file of English strings
            - cd website && yarn install && yarn run write-translations && cd ..
            # crowdin install
            - sudo apt-get install default-jre
            - wget https://artifacts.crowdin.com/repo/deb/crowdin.deb -O crowdin.deb
            - sudo dpkg -i crowdin.deb
            # translations upload/download
            - crowdin --config crowdin.yaml upload sources --auto-update -b master
            - crowdin --config crowdin.yaml download -b master
            # build and publish website
            cd website && GIT_USER=<GIT_USER> yarn run publish-gh-pages
workflows:
  version: 2
  build_and_deploy:
    jobs:
      - deploy-website:
#         filters: *filter-only-master
The crowdin command uses the crowdin.yaml file generated with the examples script. It should be placed in your project directory to configure how and what files are uploaded/downloaded.
Note that in the crowdin.yaml file, CROWDIN_PROJECT_ID and CROWDIN_API_KEY are environment variables set-up in Circle for your Crowdin project. They can be found in your Crowdin project settings.
Now, Circle will help you automatically get translations prior to building your website. The provided crowdin.yaml file will copy translated documents into website/translated_docs/, and translated versions of the i18n/en.json strings file will into i18n/${language}.json.
If you wish to use Crowdin on your machine locally, you can install the Crowdin CLI tool and run the same commands found in the circle.yaml file. The only difference is that you must set project_identifier and api_key values in the crowdin.yaml file since you will not have Circle environment variables set up.
Versioned Translations
If you wish to have translation and versioning for your documentation, add the following section to the end of your crowdin.yaml file:
  -
    source: '/website/versioned_docs/**/*.md'
    translation: '/website/translated_docs/%locale%/**/%original_file_name%'
    languages_mapping: *anchor
Translated, versioned documents will be copied into website/translated_docs/${language}/${version}/.