@intlayer/docs 7.0.4-canary.0 → 7.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/blog/ar/intlayer_with_i18next.md +68 -106
- package/blog/ar/intlayer_with_next-i18next.md +84 -288
- package/blog/ar/intlayer_with_next-intl.md +58 -337
- package/blog/ar/intlayer_with_react-i18next.md +68 -290
- package/blog/ar/intlayer_with_react-intl.md +63 -266
- package/blog/de/intlayer_with_i18next.md +77 -97
- package/blog/de/intlayer_with_next-i18next.md +69 -296
- package/blog/de/intlayer_with_next-intl.md +59 -340
- package/blog/de/intlayer_with_react-i18next.md +68 -290
- package/blog/de/intlayer_with_react-intl.md +62 -264
- package/blog/en/intlayer_with_i18next.md +36 -1638
- package/blog/en/intlayer_with_next-i18next.md +22 -847
- package/blog/en/intlayer_with_next-intl.md +32 -1053
- package/blog/en/intlayer_with_react-i18next.md +38 -764
- package/blog/en/intlayer_with_react-intl.md +42 -1018
- package/blog/en-GB/intlayer_with_i18next.md +67 -103
- package/blog/en-GB/intlayer_with_next-i18next.md +71 -292
- package/blog/en-GB/intlayer_with_next-intl.md +58 -337
- package/blog/en-GB/intlayer_with_react-i18next.md +67 -289
- package/blog/en-GB/intlayer_with_react-intl.md +61 -264
- package/blog/es/intlayer_with_i18next.md +67 -103
- package/blog/es/intlayer_with_next-i18next.md +71 -296
- package/blog/es/intlayer_with_next-intl.md +57 -338
- package/blog/es/intlayer_with_react-i18next.md +68 -290
- package/blog/es/intlayer_with_react-intl.md +62 -265
- package/blog/fr/intlayer_with_i18next.md +66 -104
- package/blog/fr/intlayer_with_next-i18next.md +82 -285
- package/blog/fr/intlayer_with_next-intl.md +57 -338
- package/blog/fr/intlayer_with_react-i18next.md +67 -289
- package/blog/fr/intlayer_with_react-intl.md +61 -264
- package/blog/hi/intlayer_with_i18next.md +68 -104
- package/blog/hi/intlayer_with_next-i18next.md +74 -299
- package/blog/hi/intlayer_with_next-intl.md +57 -239
- package/blog/hi/intlayer_with_react-i18next.md +69 -291
- package/blog/hi/intlayer_with_react-intl.md +65 -268
- package/blog/id/intlayer_with_i18next.md +126 -0
- package/blog/id/intlayer_with_next-i18next.md +142 -0
- package/blog/id/intlayer_with_next-intl.md +113 -0
- package/blog/id/intlayer_with_react-i18next.md +124 -0
- package/blog/id/intlayer_with_react-intl.md +122 -0
- package/blog/it/intlayer_with_i18next.md +67 -103
- package/blog/it/intlayer_with_next-i18next.md +71 -296
- package/blog/it/intlayer_with_next-intl.md +57 -338
- package/blog/it/intlayer_with_react-i18next.md +68 -290
- package/blog/it/intlayer_with_react-intl.md +62 -265
- package/blog/ja/intlayer_with_i18next.md +68 -103
- package/blog/ja/intlayer_with_next-i18next.md +85 -283
- package/blog/ja/intlayer_with_next-intl.md +58 -336
- package/blog/ja/intlayer_with_react-i18next.md +68 -290
- package/blog/ja/intlayer_with_react-intl.md +62 -264
- package/blog/ko/intlayer_with_i18next.md +80 -96
- package/blog/ko/intlayer_with_next-i18next.md +85 -287
- package/blog/ko/intlayer_with_next-intl.md +68 -327
- package/blog/ko/intlayer_with_react-i18next.md +68 -290
- package/blog/ko/intlayer_with_react-intl.md +64 -266
- package/blog/pl/intlayer_with_i18next.md +126 -0
- package/blog/pl/intlayer_with_next-i18next.md +142 -0
- package/blog/pl/intlayer_with_next-intl.md +111 -0
- package/blog/pl/intlayer_with_react-i18next.md +124 -0
- package/blog/pl/intlayer_with_react-intl.md +122 -0
- package/blog/pt/intlayer_with_i18next.md +67 -103
- package/blog/pt/intlayer_with_next-i18next.md +72 -293
- package/blog/pt/intlayer_with_next-intl.md +57 -256
- package/blog/pt/intlayer_with_react-i18next.md +104 -78
- package/blog/pt/intlayer_with_react-intl.md +62 -266
- package/blog/ru/intlayer_with_i18next.md +66 -104
- package/blog/ru/intlayer_with_next-i18next.md +71 -296
- package/blog/ru/intlayer_with_next-intl.md +58 -337
- package/blog/ru/intlayer_with_react-i18next.md +68 -290
- package/blog/ru/intlayer_with_react-intl.md +62 -265
- package/blog/tr/intlayer_with_i18next.md +71 -107
- package/blog/tr/intlayer_with_next-i18next.md +72 -297
- package/blog/tr/intlayer_with_next-intl.md +58 -339
- package/blog/tr/intlayer_with_react-i18next.md +69 -291
- package/blog/tr/intlayer_with_react-intl.md +63 -285
- package/blog/vi/intlayer_with_i18next.md +126 -0
- package/blog/vi/intlayer_with_next-i18next.md +142 -0
- package/blog/vi/intlayer_with_next-intl.md +111 -0
- package/blog/vi/intlayer_with_react-i18next.md +124 -0
- package/blog/vi/intlayer_with_react-intl.md +122 -0
- package/blog/zh/intlayer_with_i18next.md +67 -102
- package/blog/zh/intlayer_with_next-i18next.md +72 -296
- package/blog/zh/intlayer_with_next-intl.md +58 -336
- package/blog/zh/intlayer_with_react-i18next.md +68 -290
- package/blog/zh/intlayer_with_react-intl.md +63 -106
- package/docs/ar/plugins/sync-json.md +244 -0
- package/docs/de/plugins/sync-json.md +244 -0
- package/docs/en/intlayer_cli.md +25 -0
- package/docs/en/intlayer_with_nextjs_14.md +2 -0
- package/docs/en/intlayer_with_nextjs_15.md +2 -0
- package/docs/en/intlayer_with_nextjs_16.md +2 -0
- package/docs/en/plugins/sync-json.md +1 -1
- package/docs/en-GB/plugins/sync-json.md +244 -0
- package/docs/es/plugins/sync-json.md +244 -0
- package/docs/fr/plugins/sync-json.md +244 -0
- package/docs/hi/plugins/sync-json.md +244 -0
- package/docs/id/plugins/sync-json.md +244 -0
- package/docs/it/plugins/sync-json.md +244 -0
- package/docs/ja/plugins/sync-json.md +244 -0
- package/docs/ko/plugins/sync-json.md +244 -0
- package/docs/pl/plugins/sync-json.md +244 -0
- package/docs/pt/plugins/sync-json.md +244 -0
- package/docs/ru/plugins/sync-json.md +244 -0
- package/docs/tr/plugins/sync-json.md +245 -0
- package/docs/vi/plugins/sync-json.md +244 -0
- package/docs/zh/plugins/sync-json.md +244 -0
- package/package.json +14 -14
|
@@ -1,327 +1,123 @@
|
|
|
1
1
|
---
|
|
2
2
|
createdAt: 2025-01-02
|
|
3
|
-
updatedAt: 2025-
|
|
4
|
-
title:
|
|
5
|
-
description:
|
|
3
|
+
updatedAt: 2025-10-29
|
|
4
|
+
title: Como automatizar suas traduções JSON do react-intl usando Intlayer
|
|
5
|
+
description: Automatize suas traduções JSON com Intlayer e react-intl para uma internacionalização aprimorada em aplicações React.
|
|
6
6
|
keywords:
|
|
7
7
|
- react-intl
|
|
8
8
|
- Intlayer
|
|
9
9
|
- Internacionalização
|
|
10
|
-
-
|
|
11
|
-
-
|
|
10
|
+
- Blog
|
|
11
|
+
- i18n
|
|
12
12
|
- JavaScript
|
|
13
13
|
- React
|
|
14
|
+
- FormatJS
|
|
14
15
|
slugs:
|
|
15
16
|
- blog
|
|
16
17
|
- intlayer-with-react-intl
|
|
18
|
+
history:
|
|
19
|
+
- version: 7.0.0
|
|
20
|
+
date: 2025-10-29
|
|
21
|
+
changes: Mudança para o plugin syncJSON
|
|
17
22
|
---
|
|
18
23
|
|
|
19
|
-
#
|
|
24
|
+
# Como automatizar suas traduções JSON do react-intl usando Intlayer
|
|
20
25
|
|
|
21
|
-
|
|
26
|
+
## O que é o Intlayer?
|
|
22
27
|
|
|
23
|
-
|
|
28
|
+
**Intlayer** é uma biblioteca inovadora e de código aberto para internacionalização, projetada para resolver as limitações das soluções tradicionais de i18n. Ela oferece uma abordagem moderna para o gerenciamento de conteúdo em aplicações React.
|
|
24
29
|
|
|
25
|
-
|
|
26
|
-
- **react-intl** fornece componentes e hooks do React (como `<FormattedMessage>` e `useIntl()`) para exibir strings localizadas.
|
|
30
|
+
Veja uma comparação concreta com react-intl em nosso post no blog [react-i18next vs. react-intl vs. Intlayer](https://github.com/aymericzip/intlayer/blob/main/docs/blog/pt/react-i18next_vs_react-intl_vs_intlayer.md).
|
|
27
31
|
|
|
28
|
-
|
|
32
|
+
## Por que combinar Intlayer com react-intl?
|
|
29
33
|
|
|
30
|
-
|
|
34
|
+
Embora o Intlayer forneça uma excelente solução i18n independente (veja nosso [guia de integração com React](https://github.com/aymericzip/intlayer/blob/main/docs/docs/pt/intlayer_with_vite+react.md)), você pode querer combiná-lo com react-intl por várias razões:
|
|
31
35
|
|
|
32
|
-
|
|
36
|
+
1. **Base de código existente**: Você possui uma implementação estabelecida do react-intl e deseja migrar gradualmente para a melhor experiência de desenvolvedor do Intlayer.
|
|
37
|
+
2. **Requisitos legados**: Seu projeto requer compatibilidade com plugins ou fluxos de trabalho existentes do react-intl.
|
|
38
|
+
3. **Familiaridade da equipe**: Sua equipe está confortável com o react-intl, mas deseja um melhor gerenciamento de conteúdo.
|
|
33
39
|
|
|
34
|
-
|
|
35
|
-
Os arquivos de declaração de conteúdo do Intlayer podem viver ao lado dos seus componentes React, prevenindo traduções “órfãs” se os componentes forem movidos ou removidos. Por exemplo:
|
|
40
|
+
**Para isso, o Intlayer pode ser implementado como um adaptador para o react-intl, ajudando a automatizar suas traduções JSON em pipelines CLI ou CI/CD, testar suas traduções e muito mais.**
|
|
36
41
|
|
|
37
|
-
|
|
38
|
-
.
|
|
39
|
-
└── src
|
|
40
|
-
└── components
|
|
41
|
-
└── MyComponent
|
|
42
|
-
├── index.content.ts # Declaração de conteúdo do Intlayer
|
|
43
|
-
└── index.tsx # Componente React
|
|
44
|
-
```
|
|
42
|
+
Este guia mostra como aproveitar o sistema superior de declaração de conteúdo do Intlayer, mantendo a compatibilidade com o react-intl.
|
|
45
43
|
|
|
46
|
-
|
|
47
|
-
Cada arquivo de declaração de conteúdo coleta todas as traduções necessárias para um componente. Isso é particularmente útil em projetos TypeScript: traduções ausentes podem ser descobertas no **tempo de compilação**.
|
|
44
|
+
## Índice
|
|
48
45
|
|
|
49
|
-
|
|
50
|
-
Sempre que você adicionar ou atualizar traduções, o Intlayer regenera os arquivos JSON de mensagens. Você pode então passá-los para o `<IntlProvider>` do react-intl.
|
|
46
|
+
<TOC/>
|
|
51
47
|
|
|
52
|
-
|
|
48
|
+
## Guia passo a passo para configurar o Intlayer com react-intl
|
|
53
49
|
|
|
54
|
-
|
|
50
|
+
### Passo 1: Instalar dependências
|
|
55
51
|
|
|
56
|
-
|
|
52
|
+
Instale os pacotes necessários:
|
|
57
53
|
|
|
58
|
-
```bash
|
|
59
|
-
|
|
60
|
-
|
|
54
|
+
```bash packageManager="npm"
|
|
55
|
+
npm install intlayer @intlayer/sync-json-plugin
|
|
56
|
+
```
|
|
61
57
|
|
|
62
|
-
|
|
63
|
-
|
|
58
|
+
```bash packageManager="pnpm"
|
|
59
|
+
pnpm add intlayer @intlayer/sync-json-plugin
|
|
60
|
+
```
|
|
64
61
|
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
```bash packageManager="yarn"
|
|
63
|
+
yarn add intlayer @intlayer/sync-json-plugin
|
|
67
64
|
```
|
|
68
65
|
|
|
69
|
-
|
|
66
|
+
**Descrição dos pacotes:**
|
|
70
67
|
|
|
71
|
-
- **intlayer**:
|
|
72
|
-
-
|
|
68
|
+
- **intlayer**: Biblioteca principal para gerenciamento de internacionalização, declaração de conteúdo e construção
|
|
69
|
+
- **@intlayer/sync-json-plugin**: Plugin para exportar declarações de conteúdo do Intlayer para o formato JSON compatível com react-intl
|
|
73
70
|
|
|
74
|
-
|
|
71
|
+
### Passo 2: Implemente o plugin Intlayer para encapsular o JSON
|
|
75
72
|
|
|
76
|
-
|
|
73
|
+
Crie um arquivo de configuração do Intlayer para definir os seus locais suportados:
|
|
77
74
|
|
|
78
|
-
|
|
75
|
+
**Se você também quiser exportar dicionários JSON para react-intl**, adicione o plugin `syncJSON`:
|
|
79
76
|
|
|
80
|
-
```typescript
|
|
77
|
+
```typescript fileName="intlayer.config.ts"
|
|
81
78
|
import { Locales, type IntlayerConfig } from "intlayer";
|
|
79
|
+
import { syncJSON } from "@intlayer/sync-json-plugin";
|
|
82
80
|
|
|
83
81
|
const config: IntlayerConfig = {
|
|
84
82
|
internationalization: {
|
|
85
|
-
// Adicione quantos locais desejar
|
|
86
83
|
locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],
|
|
87
84
|
defaultLocale: Locales.ENGLISH,
|
|
88
85
|
},
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
// O diretório onde o Intlayer escreverá seus arquivos JSON de mensagens
|
|
94
|
-
reactIntlMessagesDir: "./react-intl/messages",
|
|
95
|
-
},
|
|
96
|
-
};
|
|
97
|
-
|
|
98
|
-
export default config;
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
> **Nota**: Para outras extensões de arquivo (`.mjs`, `.cjs`, `.js`), consulte a [documentação do Intlayer](https://intlayer.org/pt/doc/concept/configuration) para detalhes de uso.
|
|
102
|
-
|
|
103
|
-
---
|
|
104
|
-
|
|
105
|
-
## Criando Suas Declarações de Conteúdo do Intlayer
|
|
106
|
-
|
|
107
|
-
O Intlayer escaneia seu código (por padrão, sob `./src`) em busca de arquivos que correspondam a `*.content.{ts,tsx,js,jsx,mjs,mjx,cjs,cjx,json}`.
|
|
108
|
-
Aqui está um exemplo de **TypeScript**:
|
|
109
|
-
|
|
110
|
-
```typescript title="src/components/MyComponent/index.content.ts"
|
|
111
|
-
import { t, type Dictionary } from "intlayer";
|
|
112
|
-
|
|
113
|
-
const content = {
|
|
114
|
-
// "key" se torna a chave de mensagem de nível superior no seu arquivo JSON do react-intl
|
|
115
|
-
key: "meu-componente",
|
|
116
|
-
|
|
117
|
-
content: {
|
|
118
|
-
// Cada chamada a t() declara um campo traduzível
|
|
119
|
-
helloWorld: t({
|
|
120
|
-
en: "Hello World",
|
|
121
|
-
es: "Hola Mundo",
|
|
122
|
-
fr: "Bonjour le monde",
|
|
123
|
-
}),
|
|
124
|
-
description: t({
|
|
125
|
-
en: "This is a description",
|
|
126
|
-
fr: "Ceci est une description",
|
|
127
|
-
es: "Esta es una descripción",
|
|
86
|
+
plugins: [
|
|
87
|
+
syncJSON({
|
|
88
|
+
source: ({ key, locale }) => `./intl/messages/${locale}/${key}.json`,
|
|
128
89
|
}),
|
|
129
|
-
|
|
130
|
-
} satisfies Dictionary;
|
|
131
|
-
|
|
132
|
-
export default content;
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
Se preferir JSON ou diferentes variantes JS (`.cjs`, `.mjs`), a estrutura é em grande parte a mesma , veja [documentação do Intlayer sobre declaração de conteúdo](https://intlayer.org/pt/doc/concept/content).
|
|
136
|
-
|
|
137
|
-
---
|
|
138
|
-
|
|
139
|
-
## Construindo as Mensagens do react-intl
|
|
140
|
-
|
|
141
|
-
Para gerar os arquivos JSON de mensagens reais para **react-intl**, execute:
|
|
142
|
-
|
|
143
|
-
```bash
|
|
144
|
-
# com npm
|
|
145
|
-
npx intlayer dictionaries build
|
|
146
|
-
|
|
147
|
-
# com yarn
|
|
148
|
-
yarn intlayer build
|
|
149
|
-
|
|
150
|
-
# com pnpm
|
|
151
|
-
pnpm intlayer build
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
Isso escaneia todos os arquivos `*.content.*`, os compila e grava os resultados no diretório especificado no seu **`intlayer.config.ts`** , neste exemplo, `./react-intl/messages`.
|
|
155
|
-
Uma saída típica pode parecer com:
|
|
156
|
-
|
|
157
|
-
```bash
|
|
158
|
-
.
|
|
159
|
-
└── react-intl
|
|
160
|
-
└── messages
|
|
161
|
-
├── en.json
|
|
162
|
-
├── fr.json
|
|
163
|
-
└── es.json
|
|
164
|
-
```
|
|
165
|
-
|
|
166
|
-
Cada arquivo é um objeto JSON cujas **chaves de nível superior** correspondem a cada **`content.key`** das suas declarações. As **subchaves** (como `helloWorld`) refletem as traduções declaradas dentro daquele item de conteúdo.
|
|
167
|
-
|
|
168
|
-
Por exemplo, o **en.json** pode parecer assim:
|
|
169
|
-
|
|
170
|
-
```json
|
|
171
|
-
{
|
|
172
|
-
"meu-componente": {
|
|
173
|
-
"helloWorld": "Hello World",
|
|
174
|
-
"description": "This is a description"
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
```
|
|
178
|
-
|
|
179
|
-
---
|
|
180
|
-
|
|
181
|
-
## Inicializando o react-intl na Sua Aplicação React
|
|
182
|
-
|
|
183
|
-
### 1. Carregue as Mensagens Geradas
|
|
184
|
-
|
|
185
|
-
Onde você configura o componente raiz da sua aplicação (por exemplo, `src/main.tsx` ou `src/index.tsx`), você precisará:
|
|
186
|
-
|
|
187
|
-
1. **Importar** os arquivos de mensagem gerados (estaticamente ou dinamicamente).
|
|
188
|
-
2. **Fornecer** a eles para o `<IntlProvider>` do `react-intl`.
|
|
189
|
-
|
|
190
|
-
Uma abordagem simples é importá-los **estaticamente**:
|
|
191
|
-
|
|
192
|
-
```typescript title="src/index.tsx"
|
|
193
|
-
import React from "react";
|
|
194
|
-
import ReactDOM from "react-dom/client";
|
|
195
|
-
import { IntlProvider } from "react-intl";
|
|
196
|
-
import App from "./App";
|
|
197
|
-
|
|
198
|
-
// Importar os arquivos JSON da saída de compilação.
|
|
199
|
-
// Alternativamente, você pode importar dinamicamente com base no idioma escolhido pelo usuário.
|
|
200
|
-
import en from "../react-intl/messages/en.json";
|
|
201
|
-
import fr from "../react-intl/messages/fr.json";
|
|
202
|
-
import es from "../react-intl/messages/es.json";
|
|
203
|
-
|
|
204
|
-
// Se você tiver um mecanismo para detectar o idioma do usuário, defina-o aqui.
|
|
205
|
-
// Para simplicidade, vamos escolher o inglês.
|
|
206
|
-
const locale = "en";
|
|
207
|
-
|
|
208
|
-
// Compilar mensagens em um objeto (ou selecioná-las dinamicamente)
|
|
209
|
-
const messagesRecord: Record<string, Record<string, any>> = {
|
|
210
|
-
en,
|
|
211
|
-
fr,
|
|
212
|
-
es,
|
|
90
|
+
],
|
|
213
91
|
};
|
|
214
92
|
|
|
215
|
-
|
|
216
|
-
<React.StrictMode>
|
|
217
|
-
<IntlProvider locale={locale} messages={messagesRecord[locale]}>
|
|
218
|
-
<App />
|
|
219
|
-
</IntlProvider>
|
|
220
|
-
</React.StrictMode>
|
|
221
|
-
);
|
|
222
|
-
```
|
|
223
|
-
|
|
224
|
-
> **Dica**: Para projetos reais, você pode:
|
|
225
|
-
>
|
|
226
|
-
> - Carregar dinamicamente as mensagens JSON em tempo de execução.
|
|
227
|
-
> - Usar detecção de localidade baseada em ambiente, no navegador ou na conta do usuário.
|
|
228
|
-
|
|
229
|
-
### 2. Usar `<FormattedMessage>` ou `useIntl()`
|
|
230
|
-
|
|
231
|
-
Uma vez que suas mensagens estejam carregadas no `<IntlProvider>`, qualquer componente filho pode usar react-intl para acessar strings localizadas. Existem duas abordagens principais:
|
|
232
|
-
|
|
233
|
-
- **Componente `<FormattedMessage>`**
|
|
234
|
-
- **Hook `useIntl()`**
|
|
235
|
-
|
|
236
|
-
---
|
|
237
|
-
|
|
238
|
-
## Usando Traduções em Componentes React
|
|
239
|
-
|
|
240
|
-
### Abordagem A: `<FormattedMessage>`
|
|
241
|
-
|
|
242
|
-
Para uso rápido em linha:
|
|
243
|
-
|
|
244
|
-
```tsx title="src/components/MyComponent/index.tsx"
|
|
245
|
-
import React from "react";
|
|
246
|
-
import { FormattedMessage } from "react-intl";
|
|
247
|
-
|
|
248
|
-
export default function MyComponent() {
|
|
249
|
-
return (
|
|
250
|
-
<div>
|
|
251
|
-
<h1>
|
|
252
|
-
{/* “meu-componente.helloWorld” referencia a chave de en.json, fr.json, etc. */}
|
|
253
|
-
<FormattedMessage id="meu-componente.helloWorld" />
|
|
254
|
-
</h1>
|
|
255
|
-
|
|
256
|
-
<p>
|
|
257
|
-
<FormattedMessage id="meu-componente.description" />
|
|
258
|
-
</p>
|
|
259
|
-
</div>
|
|
260
|
-
);
|
|
261
|
-
}
|
|
262
|
-
```
|
|
263
|
-
|
|
264
|
-
> A prop **`id`** em `<FormattedMessage>` deve corresponder à **chave de nível superior** (`meu-componente`) mais quaisquer subchaves (`helloWorld`).
|
|
265
|
-
|
|
266
|
-
### Abordagem B: `useIntl()`
|
|
267
|
-
|
|
268
|
-
Para um uso mais dinâmico:
|
|
269
|
-
|
|
270
|
-
```tsx title="src/components/MyComponent/index.tsx"
|
|
271
|
-
import React from "react";
|
|
272
|
-
import { useIntl } from "react-intl";
|
|
273
|
-
|
|
274
|
-
export default function MyComponent() {
|
|
275
|
-
const intl = useIntl();
|
|
276
|
-
|
|
277
|
-
return (
|
|
278
|
-
<div>
|
|
279
|
-
<h1>{intl.formatMessage({ id: "meu-componente.helloWorld" })}</h1>
|
|
280
|
-
<p>{intl.formatMessage({ id: "meu-componente.description" })}</p>
|
|
281
|
-
</div>
|
|
282
|
-
);
|
|
283
|
-
}
|
|
93
|
+
export default config;
|
|
284
94
|
```
|
|
285
95
|
|
|
286
|
-
|
|
96
|
+
O plugin `syncJSON` irá automaticamente encapsular o JSON. Ele irá ler e escrever os arquivos JSON sem alterar a arquitetura do conteúdo.
|
|
287
97
|
|
|
288
|
-
|
|
98
|
+
Se você quiser fazer coexistir esse JSON com arquivos de declaração de conteúdo do Intlayer (arquivos `.content`), o Intlayer procederá da seguinte forma:
|
|
289
99
|
|
|
290
|
-
|
|
100
|
+
1. carregar tanto os arquivos JSON quanto os arquivos de declaração de conteúdo e transformá-los em um dicionário do Intlayer.
|
|
291
101
|
|
|
292
|
-
|
|
293
|
-
2. Execute novamente `intlayer build` para regenerar os arquivos JSON sob `./react-intl/messages`.
|
|
294
|
-
3. O React (e o react-intl) buscará as atualizações da próxima vez que você reconstruir ou recarregar sua aplicação.
|
|
102
|
+
2. se houver conflitos entre o JSON e os arquivos de declaração de conteúdo, o Intlayer irá processar a mesclagem de todos esses dicionários. Dependendo da prioridade dos plugins e da do arquivo de declaração de conteúdo (todos são configuráveis).
|
|
295
103
|
|
|
296
|
-
|
|
104
|
+
Se alterações forem feitas usando o CLI para traduzir o JSON, ou usando o CMS, o Intlayer atualizará o arquivo JSON com as novas traduções.
|
|
297
105
|
|
|
298
|
-
|
|
106
|
+
Para ver mais detalhes sobre o plugin `syncJSON`, por favor consulte a [documentação do plugin syncJSON](https://github.com/aymericzip/intlayer/blob/main/docs/docs/pt/plugins/sync-json.md).
|
|
299
107
|
|
|
300
|
-
|
|
108
|
+
## Configuração do Git
|
|
301
109
|
|
|
302
|
-
|
|
110
|
+
É recomendado ignorar os arquivos gerados automaticamente pelo Intlayer:
|
|
303
111
|
|
|
304
|
-
```
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
// ...
|
|
308
|
-
},
|
|
309
|
-
"include": ["src", "types"],
|
|
310
|
-
}
|
|
112
|
+
```plaintext fileName=".gitignore"
|
|
113
|
+
# Ignorar arquivos gerados pelo Intlayer
|
|
114
|
+
.intlayer
|
|
311
115
|
```
|
|
312
116
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
---
|
|
316
|
-
|
|
317
|
-
## Configuração do Git
|
|
117
|
+
Esses arquivos podem ser regenerados durante o seu processo de build e não precisam ser commitados no controle de versão.
|
|
318
118
|
|
|
319
|
-
|
|
119
|
+
### Extensão VS Code
|
|
320
120
|
|
|
321
|
-
|
|
322
|
-
# Ignorar artefatos de construção do intlayer
|
|
323
|
-
.intlayer
|
|
324
|
-
react-intl
|
|
325
|
-
```
|
|
121
|
+
Para uma melhor experiência de desenvolvimento, instale a **Extensão oficial Intlayer para VS Code**:
|
|
326
122
|
|
|
327
|
-
|
|
123
|
+
[Instalar no VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=intlayer.intlayer-vs-code-extension)
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
createdAt: 2024-12-24
|
|
3
|
-
updatedAt: 2025-
|
|
4
|
-
title:
|
|
5
|
-
description:
|
|
3
|
+
updatedAt: 2025-10-29
|
|
4
|
+
title: Как автоматизировать ваши JSON-переводы i18next с помощью Intlayer
|
|
5
|
+
description: Автоматизируйте ваши JSON-переводы с помощью Intlayer и i18next для улучшенной интернационализации в JavaScript-приложениях.
|
|
6
6
|
keywords:
|
|
7
7
|
- Intlayer
|
|
8
8
|
- i18next
|
|
@@ -14,149 +14,111 @@ keywords:
|
|
|
14
14
|
- Next.js
|
|
15
15
|
- JavaScript
|
|
16
16
|
- TypeScript
|
|
17
|
+
- Миграция
|
|
18
|
+
- Интеграция
|
|
17
19
|
slugs:
|
|
18
20
|
- blog
|
|
19
21
|
- intlayer-with-i18next
|
|
22
|
+
history:
|
|
23
|
+
- version: 7.0.0
|
|
24
|
+
date: 2025-10-29
|
|
25
|
+
changes: Переход на плагин syncJSON
|
|
20
26
|
---
|
|
21
27
|
|
|
22
|
-
#
|
|
28
|
+
# Как автоматизировать ваши JSON-переводы i18next с помощью Intlayer
|
|
23
29
|
|
|
24
|
-
|
|
30
|
+
## Что такое Intlayer?
|
|
25
31
|
|
|
26
|
-
Intlayer
|
|
32
|
+
**Intlayer** — это инновационная, открытая библиотека для интернационализации, созданная для устранения недостатков традиционных решений i18n. Она предлагает современный подход к управлению контентом в JavaScript-приложениях.
|
|
27
33
|
|
|
28
|
-
|
|
34
|
+
Смотрите конкретное сравнение с i18next в нашем блоге [next-i18next vs. next-intl vs. Intlayer](https://github.com/aymericzip/intlayer/blob/main/docs/blog/ru/next-i18next_vs_next-intl_vs_intlayer.md).
|
|
29
35
|
|
|
30
|
-
|
|
36
|
+
## Почему стоит сочетать Intlayer с i18next?
|
|
31
37
|
|
|
32
|
-
|
|
38
|
+
Хотя Intlayer предоставляет отличное самостоятельное решение для i18n (см. наше руководство по интеграции с Next.js [Next.js integration guide](https://github.com/aymericzip/intlayer/blob/main/docs/docs/ru/intlayer_with_nextjs_16.md)), вы можете захотеть сочетать его с i18next по нескольким причинам:
|
|
33
39
|
|
|
34
|
-
|
|
35
|
-
|
|
40
|
+
1. **Существующая кодовая база**: У вас уже есть реализованная система i18next, и вы хотите постепенно перейти на улучшенный опыт разработки с Intlayer.
|
|
41
|
+
2. **Требования наследия**: Ваш проект требует совместимости с существующими плагинами или рабочими процессами i18next.
|
|
42
|
+
3. **Знакомство команды**: Ваша команда привыкла к i18next, но хочет улучшить управление контентом.
|
|
36
43
|
|
|
37
|
-
|
|
44
|
+
**Для этого Intlayer может быть реализован как адаптер для i18next, чтобы помочь автоматизировать ваши JSON-переводы в CLI или CI/CD пайплайнах, тестировать переводы и многое другое.**
|
|
38
45
|
|
|
39
|
-
|
|
46
|
+
В этом руководстве показано, как использовать превосходную систему декларации контента Intlayer, сохраняя совместимость с i18next.
|
|
40
47
|
|
|
41
|
-
|
|
48
|
+
## Содержание
|
|
42
49
|
|
|
43
|
-
|
|
50
|
+
<TOC/>
|
|
44
51
|
|
|
45
|
-
|
|
52
|
+
## Пошаговое руководство по настройке Intlayer с i18next
|
|
46
53
|
|
|
47
|
-
|
|
54
|
+
### Шаг 1: Установка зависимостей
|
|
48
55
|
|
|
49
|
-
|
|
56
|
+
Установите необходимые пакеты:
|
|
50
57
|
|
|
51
|
-
|
|
58
|
+
```bash packageManager="npm"
|
|
59
|
+
npm install intlayer @intlayer/sync-json-plugin
|
|
60
|
+
```
|
|
52
61
|
|
|
53
|
-
|
|
62
|
+
```bash packageManager="pnpm"
|
|
63
|
+
pnpm add intlayer @intlayer/sync-json-plugin
|
|
64
|
+
```
|
|
54
65
|
|
|
55
|
-
|
|
66
|
+
```bash packageManager="yarn"
|
|
67
|
+
yarn add intlayer @intlayer/sync-json-plugin
|
|
68
|
+
```
|
|
56
69
|
|
|
57
|
-
|
|
70
|
+
**Описание пакетов:**
|
|
58
71
|
|
|
59
|
-
|
|
72
|
+
- **intlayer**: Основная библиотека для управления интернационализацией, декларации контента и сборки
|
|
73
|
+
- **@intlayer/sync-json-plugin**: Плагин для экспорта деклараций контента Intlayer в JSON-формат, совместимый с i18next
|
|
60
74
|
|
|
61
|
-
|
|
75
|
+
### Шаг 2: Реализация плагина Intlayer для обертки JSON
|
|
62
76
|
|
|
63
|
-
|
|
64
|
-
import { Locales, type IntlayerConfig } from "intlayer";
|
|
77
|
+
Создайте файл конфигурации Intlayer для определения поддерживаемых локалей:
|
|
65
78
|
|
|
66
|
-
|
|
67
|
-
content: {
|
|
68
|
-
// Укажите, что Intlayer будет экспортировать как словари Intlayer, так и i18next
|
|
69
|
-
dictionaryOutput: ["intlayer", "i18next"],
|
|
70
|
-
// Относительный путь от корня проекта к директории, куда будут экспортироваться словари i18n
|
|
71
|
-
i18nextResourcesDir: "./i18next/dictionaries",
|
|
72
|
-
},
|
|
73
|
-
};
|
|
79
|
+
**Если вы хотите также экспортировать JSON-словари для i18next**, добавьте плагин `syncJSON`:
|
|
74
80
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
```javascript fileName="intlayer.config.mjs" codeFormat="esm"
|
|
79
|
-
import { Locales } from "intlayer";
|
|
81
|
+
```typescript fileName="intlayer.config.ts"
|
|
82
|
+
import { Locales, type IntlayerConfig } from "intlayer";
|
|
83
|
+
import { syncJSON } from "@intlayer/sync-json-plugin";
|
|
80
84
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
dictionaryOutput: ["intlayer", "i18next"],
|
|
86
|
-
// Относительный путь от корня проекта к директории, куда будут экспортироваться словари i18n
|
|
87
|
-
i18nextResourcesDir: "./i18next/dictionaries",
|
|
85
|
+
const config: IntlayerConfig = {
|
|
86
|
+
internationalization: {
|
|
87
|
+
locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],
|
|
88
|
+
defaultLocale: Locales.ENGLISH,
|
|
88
89
|
},
|
|
90
|
+
plugins: [
|
|
91
|
+
syncJSON({
|
|
92
|
+
source: ({ key, locale }) => `./intl/messages/${locale}/${key}.json`,
|
|
93
|
+
}),
|
|
94
|
+
],
|
|
89
95
|
};
|
|
90
96
|
|
|
91
97
|
export default config;
|
|
92
98
|
```
|
|
93
99
|
|
|
94
|
-
|
|
95
|
-
const { Locales } = require("intlayer");
|
|
96
|
-
|
|
97
|
-
/** @type {import('intlayer').IntlayerConfig} */
|
|
98
|
-
const config = {
|
|
99
|
-
content: {
|
|
100
|
-
// Укажите, что Intlayer будет экспортировать как словари Intlayer, так и i18next
|
|
101
|
-
dictionaryOutput: ["intlayer", "i18next"],
|
|
102
|
-
// Относительный путь от корня проекта к директории, куда будут экспортироваться словари i18n
|
|
103
|
-
i18nextResourcesDir: "./i18next/dictionaries",
|
|
104
|
-
},
|
|
105
|
-
};
|
|
106
|
-
|
|
107
|
-
module.exports = config;
|
|
108
|
-
```
|
|
100
|
+
Плагин `syncJSON` автоматически обернет JSON. Он будет читать и записывать JSON-файлы без изменения архитектуры контента.
|
|
109
101
|
|
|
110
|
-
|
|
102
|
+
Если вы хотите, чтобы JSON сосуществовал с файлами декларации контента Intlayer (`.content` файлы), Intlayer будет работать следующим образом:
|
|
111
103
|
|
|
112
|
-
|
|
104
|
+
1. загрузит как JSON, так и файлы декларации контента и преобразует их в словарь Intlayer.
|
|
105
|
+
2. если возникают конфликты между JSON и файлами декларации контента, Intlayer выполнит слияние всех словарей. В зависимости от приоритета плагинов и файла декларации контента (все настраивается).
|
|
113
106
|
|
|
114
|
-
|
|
107
|
+
Если изменения вносятся с помощью CLI для перевода JSON или через CMS, Intlayer обновит JSON-файл с новыми переводами.
|
|
115
108
|
|
|
116
|
-
|
|
117
|
-
// i18n/client.ts
|
|
109
|
+
## Конфигурация Git
|
|
118
110
|
|
|
119
|
-
|
|
120
|
-
import resourcesToBackend from "i18next-resources-to-backend";
|
|
111
|
+
Рекомендуется игнорировать автоматически сгенерированные файлы Intlayer:
|
|
121
112
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
resourcesToBackend(
|
|
126
|
-
(language: string, namespace: string) =>
|
|
127
|
-
import(`../i18next/dictionaries/${language}/${namespace}.json`)
|
|
128
|
-
)
|
|
129
|
-
);
|
|
113
|
+
```plaintext fileName=".gitignore"
|
|
114
|
+
# Игнорировать файлы, сгенерированные Intlayer
|
|
115
|
+
.intlayer
|
|
130
116
|
```
|
|
131
117
|
|
|
132
|
-
|
|
133
|
-
// i18n/client.mjs
|
|
134
|
-
|
|
135
|
-
import i18next from "i18next";
|
|
136
|
-
import resourcesToBackend from "i18next-resources-to-backend";
|
|
118
|
+
Эти файлы могут быть восстановлены во время процесса сборки и не требуют добавления в систему контроля версий.
|
|
137
119
|
|
|
138
|
-
|
|
139
|
-
// Ваша конфигурация i18next
|
|
140
|
-
.use(
|
|
141
|
-
resourcesToBackend(
|
|
142
|
-
(language, namespace) =>
|
|
143
|
-
import(`../i18next/dictionaries/${language}/${namespace}.json`)
|
|
144
|
-
)
|
|
145
|
-
);
|
|
146
|
-
```
|
|
120
|
+
### Расширение VS Code
|
|
147
121
|
|
|
148
|
-
|
|
149
|
-
// i18n/client.cjs
|
|
122
|
+
Для улучшения опыта разработчика установите официальное **расширение Intlayer для VS Code**:
|
|
150
123
|
|
|
151
|
-
|
|
152
|
-
const resourcesToBackend = require("i18next-resources-to-backend");
|
|
153
|
-
|
|
154
|
-
i18next
|
|
155
|
-
// Ваша конфигурация i18next
|
|
156
|
-
.use(
|
|
157
|
-
resourcesToBackend(
|
|
158
|
-
(language, namespace) =>
|
|
159
|
-
import(`../i18next/dictionaries/${language}/${namespace}.json`)
|
|
160
|
-
)
|
|
161
|
-
);
|
|
162
|
-
```
|
|
124
|
+
[Установить из магазина расширений VS Code](https://marketplace.visualstudio.com/items?itemName=intlayer.intlayer-vs-code-extension)
|