Translations & Localization
Docusaurus allows for easy translation functionality using Crowdin. Los archivos de documentación escritos en inglés se cargan en Crowdin para su traducción por los usuarios de una comunidad. Las páginas de nivel superior escritas con cadenas en inglés se pueden traducir envolviendo cualquier cadena que quiera traducir en una etiqueta <translate>
. Otros títulos y etiquetas también se encontrarán y se traducirán correctamente.
Configuraciones de Traducción de Docusaurus
To generate example files for translations with Docusaurus, run the examples
script with the command line argument translations
:
npm run examples translations
o
yarn examples translations
Esto creará los siguientes archivos:
pages/en/help-with-translations.js
languages.js
../crowdin.yaml
- El archivo
pages/en/help-with-translations.js
incluye la misma página de ayuda inicial generada por el scriptexamples
, pero ahora incluye etiquetas de traducción.
Generally, you will use
help-with-translations.js
as a guide to enable translations in your other pages, but not actually commit the file to your repo (i.e., you can delete it). However, if you want a Help page, and you currently do not have one, you can rename this file tohelp.js
and use it as a starting point.
The
languages.js
file tells Docusaurus what languages you want to enable for your site. By default, we expect English to be enabled.The
crowdin.yaml
file is used to configure Crowdin integration, and is copied up one level into your Docusaurus project repo. If your Docusaurus project resides in/project/website
, thencrowdin.yaml
will be copied to/project/crowdin.yaml
.
Traduciendo sus documentos existentes
Your documentation files (e.g., the .md
files that live in your docs
directory) do not need to be changed or moved to support translations. They will be uploaded to Crowdin to be translated directly.
Habilitación de traducciones en páginas
Las páginas le permiten personalizar el diseño y el contenido específico de las páginas, como una página de índice personalizada o una página de ayuda.
Pages with text that you want translated should be placed in website/pages/en
directory.
Ajuste las cadenas que desee traducir en una etiqueta <translate>
y agregue la siguiente instrucción require
al principio del archivo:
...
const translate = require('../../server/translate.js').translate;
...
<h2>
<translate>This header will be translated</translate>
</h2>
...
También puede incluir un atributo de descripción opcional para dar más contexto a un traductor sobre cómo traducir la cadena:
<p>
<translate desc="flower, not verb">Rose</translate>
<p>
The
<translate>
tag generally works well on pure strings. If you have a string like "Docusaurus currently provides support to help your website use translations", wrapping the<translation>
tag around that entire string will cause issues because of the markdown linking, etc. Your options are to not translate those strings, or spread a bunch of<translate>
tags amongst the pure substrings of that string.
Reunir cadenas para traducir
Las cadenas dentro de las páginas localizadas se deben extraer y proporcionar a Crowdin.
Add the following script to your website/package.json
file, if it does not exist already:
{
...
"scripts": {
"write-translations": "docusaurus-write-translations"
},
...
}
La ejecución del script generará un archivo website/i18n/en.json
que contiene todas las cadenas que se traducirán del inglés a otros idiomas.
El script incluirá texto de los siguientes lugares:
title
ysidebar_label
cadenas en los encabezados de documentos de markdown- nombres de categoría en
sidebars.json
- tagline en
siteConfig.js
- enlace de encabezado
label
cadenas ensiteConfig.js
- cadenas incluidas en la etiqueta
<translate>
etiquetas en cualquier archivo.js
dentro depages
Cómo se traducen las cadenas
Docusaurus en sí no hace ninguna traducción de un idioma a otro. En cambio, integra Crowdin para cargar traducciones y luego descarga los archivos adecuadamente traducidos de Crowdin.
Cómo utiliza Docusaurus las cadenas de traducción
Esta sección proporciona un contexto sobre cómo funcionan las traducciones en Docusaurus.
Cadenas
Un sitio de Docusaurus tiene muchas cadenas usadas a lo largo de él que requieren localización. Sin embargo, mantener una lista de cadenas usadas en un sitio puede ser laborioso. Docusaurus simplifies this by centralizing strings.
La navegación del encabezado, por ejemplo, puede tener enlaces a 'Inicio' o a su 'Blog'. Esta y otras cadenas encontradas en los encabezados y barras laterales de las páginas se extraen y se colocan en i18n/en.json
. When your files are translated, say into Spanish, a i18n/es-ES.json
file will be downloaded from Crowdin. Luego, cuando se generen las páginas en español, Docusaurus reemplazará la versión en inglés de las cadenas correspondientes con cadenas traducidas del archivo correspondiente de cadenas localizadas (por ejemplo, en un sitio habilitado en español, 'Ayuda' se convertirá en 'Ayuda').
Archivos de Markdown
Para los propios archivos de documentación, las versiones traducidas de estos archivos se descargan y luego se procesan a través de la plantilla de diseño adecuada.
Otras páginas
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. Puede usar Crowdin's guides para obtener más información sobre el flujo de trabajo de las traducciones. 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
crowdin
command 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"
},
Sincronización manual de archivos
You will always want to upload your markdown files and translatable strings first and the 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_ID
is the name of your Crowdin project. e.g., for https://crowdin.com/project/docusaurus/, that variable would be set todocusaurus
.YOUR_CROWDIN_API_KEY
is a unique key that is like a password. You can find it in theAPI
tab 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.bashrc
or.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/i18n
orwebsite/translated_docs
directory as part of your repo. So you can can addwebsite/i18n/*
andwebsite/translated_docs
to your.gitignore
file.
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 circle.yml
file in your project directory to include steps to upload English files to be translated and download translated files using the Crowdin CLI. Aquí hay un archivo de ejemplo circle.yml
:
machine:
node:
version: 6.10.3
npm:
version: 3.10.10
test:
override:
- "true"
deployment:
website:
branch: master
commands:
# configure git user
- git config --global user.email "test-site-bot@users.noreply.github.com"
- git config --global user.name "Website Deployment Script"
- echo "machine github.com login test-site-bot password $GITHUB_TOKEN" > ~/.netrc
# install Docusaurus and generate file of English strings
- cd website && npm install && npm 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=test-site-bot npm run publish-gh-pages
El comando crowdin
usa el archivo crowdin.yaml
generado con el script examples
. Debe colocarse en el directorio de su proyecto para configurar cómo y qué archivos se cargan/descargan.
Tenga en cuenta que en el archivo crowdin.yaml
, CROWDIN_PROJECT_ID
y CROWDIN_API_KEY
se configuran las variables de entorno en Circle para su proyecto Crowdin. Se pueden encontrar en la configuración de tu proyecto Crowdin.
Ahora, Circle lo ayudará a obtener traducciones automáticamente antes de construir su sitio web. El archivo crowdin.yaml
provisto copiará los documentos traducidos en website/translated_docs/
, y las versiones traducidas del archivo i18n/en.json
en i18n/${language}.json
.
Si desea usar Crowdin en su máquina localmente, puede instalar la herramienta Crowdin CLI y ejecutar los mismos comandos que se encuentran en el archivo circle.yaml
. La única diferencia es que debe establecer los valores project_identifier
y api_key
en el archivo crowdin.yaml
, ya que no tendrá configuradas las variables de entorno Circle.
Versiones y Traducciones
Si desea tener traducción y versiones para su documentación, agregue la siguiente sección al final de su archivo crowdin.yaml
:
-
source: '/website/versioned_docs/**/*.md'
translation: '/website/translated_docs/%locale%/**/%original_file_name%'
languages_mapping: *anchor
Los documentos traducidos y versionados se copiarán en el sitio web website/translated_docs/${language}/${version}/
.