@intlayer/docs 7.0.4-canary.0 → 7.0.5

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.
Files changed (107) hide show
  1. package/blog/ar/intlayer_with_i18next.md +68 -106
  2. package/blog/ar/intlayer_with_next-i18next.md +84 -288
  3. package/blog/ar/intlayer_with_next-intl.md +58 -337
  4. package/blog/ar/intlayer_with_react-i18next.md +68 -290
  5. package/blog/ar/intlayer_with_react-intl.md +63 -266
  6. package/blog/de/intlayer_with_i18next.md +77 -97
  7. package/blog/de/intlayer_with_next-i18next.md +69 -296
  8. package/blog/de/intlayer_with_next-intl.md +59 -340
  9. package/blog/de/intlayer_with_react-i18next.md +68 -290
  10. package/blog/de/intlayer_with_react-intl.md +62 -264
  11. package/blog/en/intlayer_with_i18next.md +36 -1638
  12. package/blog/en/intlayer_with_next-i18next.md +22 -847
  13. package/blog/en/intlayer_with_next-intl.md +32 -1053
  14. package/blog/en/intlayer_with_react-i18next.md +38 -764
  15. package/blog/en/intlayer_with_react-intl.md +42 -1018
  16. package/blog/en-GB/intlayer_with_i18next.md +67 -103
  17. package/blog/en-GB/intlayer_with_next-i18next.md +71 -292
  18. package/blog/en-GB/intlayer_with_next-intl.md +58 -337
  19. package/blog/en-GB/intlayer_with_react-i18next.md +67 -289
  20. package/blog/en-GB/intlayer_with_react-intl.md +61 -264
  21. package/blog/es/intlayer_with_i18next.md +67 -103
  22. package/blog/es/intlayer_with_next-i18next.md +71 -296
  23. package/blog/es/intlayer_with_next-intl.md +57 -338
  24. package/blog/es/intlayer_with_react-i18next.md +68 -290
  25. package/blog/es/intlayer_with_react-intl.md +62 -265
  26. package/blog/fr/intlayer_with_i18next.md +66 -104
  27. package/blog/fr/intlayer_with_next-i18next.md +82 -285
  28. package/blog/fr/intlayer_with_next-intl.md +57 -338
  29. package/blog/fr/intlayer_with_react-i18next.md +67 -289
  30. package/blog/fr/intlayer_with_react-intl.md +61 -264
  31. package/blog/hi/intlayer_with_i18next.md +68 -104
  32. package/blog/hi/intlayer_with_next-i18next.md +74 -299
  33. package/blog/hi/intlayer_with_next-intl.md +57 -239
  34. package/blog/hi/intlayer_with_react-i18next.md +69 -291
  35. package/blog/hi/intlayer_with_react-intl.md +65 -268
  36. package/blog/id/intlayer_with_i18next.md +126 -0
  37. package/blog/id/intlayer_with_next-i18next.md +142 -0
  38. package/blog/id/intlayer_with_next-intl.md +113 -0
  39. package/blog/id/intlayer_with_react-i18next.md +124 -0
  40. package/blog/id/intlayer_with_react-intl.md +122 -0
  41. package/blog/it/intlayer_with_i18next.md +67 -103
  42. package/blog/it/intlayer_with_next-i18next.md +71 -296
  43. package/blog/it/intlayer_with_next-intl.md +57 -338
  44. package/blog/it/intlayer_with_react-i18next.md +68 -290
  45. package/blog/it/intlayer_with_react-intl.md +62 -265
  46. package/blog/ja/intlayer_with_i18next.md +68 -103
  47. package/blog/ja/intlayer_with_next-i18next.md +85 -283
  48. package/blog/ja/intlayer_with_next-intl.md +58 -336
  49. package/blog/ja/intlayer_with_react-i18next.md +68 -290
  50. package/blog/ja/intlayer_with_react-intl.md +62 -264
  51. package/blog/ko/intlayer_with_i18next.md +80 -96
  52. package/blog/ko/intlayer_with_next-i18next.md +85 -287
  53. package/blog/ko/intlayer_with_next-intl.md +68 -327
  54. package/blog/ko/intlayer_with_react-i18next.md +68 -290
  55. package/blog/ko/intlayer_with_react-intl.md +64 -266
  56. package/blog/pl/intlayer_with_i18next.md +126 -0
  57. package/blog/pl/intlayer_with_next-i18next.md +142 -0
  58. package/blog/pl/intlayer_with_next-intl.md +111 -0
  59. package/blog/pl/intlayer_with_react-i18next.md +124 -0
  60. package/blog/pl/intlayer_with_react-intl.md +122 -0
  61. package/blog/pt/intlayer_with_i18next.md +67 -103
  62. package/blog/pt/intlayer_with_next-i18next.md +72 -293
  63. package/blog/pt/intlayer_with_next-intl.md +57 -256
  64. package/blog/pt/intlayer_with_react-i18next.md +104 -78
  65. package/blog/pt/intlayer_with_react-intl.md +62 -266
  66. package/blog/ru/intlayer_with_i18next.md +66 -104
  67. package/blog/ru/intlayer_with_next-i18next.md +71 -296
  68. package/blog/ru/intlayer_with_next-intl.md +58 -337
  69. package/blog/ru/intlayer_with_react-i18next.md +68 -290
  70. package/blog/ru/intlayer_with_react-intl.md +62 -265
  71. package/blog/tr/intlayer_with_i18next.md +71 -107
  72. package/blog/tr/intlayer_with_next-i18next.md +72 -297
  73. package/blog/tr/intlayer_with_next-intl.md +58 -339
  74. package/blog/tr/intlayer_with_react-i18next.md +69 -291
  75. package/blog/tr/intlayer_with_react-intl.md +63 -285
  76. package/blog/vi/intlayer_with_i18next.md +126 -0
  77. package/blog/vi/intlayer_with_next-i18next.md +142 -0
  78. package/blog/vi/intlayer_with_next-intl.md +111 -0
  79. package/blog/vi/intlayer_with_react-i18next.md +124 -0
  80. package/blog/vi/intlayer_with_react-intl.md +122 -0
  81. package/blog/zh/intlayer_with_i18next.md +67 -102
  82. package/blog/zh/intlayer_with_next-i18next.md +72 -296
  83. package/blog/zh/intlayer_with_next-intl.md +58 -336
  84. package/blog/zh/intlayer_with_react-i18next.md +68 -290
  85. package/blog/zh/intlayer_with_react-intl.md +63 -106
  86. package/docs/ar/plugins/sync-json.md +244 -0
  87. package/docs/de/plugins/sync-json.md +244 -0
  88. package/docs/en/intlayer_cli.md +25 -0
  89. package/docs/en/intlayer_with_nextjs_14.md +2 -0
  90. package/docs/en/intlayer_with_nextjs_15.md +2 -0
  91. package/docs/en/intlayer_with_nextjs_16.md +2 -0
  92. package/docs/en/plugins/sync-json.md +1 -1
  93. package/docs/en-GB/plugins/sync-json.md +244 -0
  94. package/docs/es/plugins/sync-json.md +244 -0
  95. package/docs/fr/plugins/sync-json.md +244 -0
  96. package/docs/hi/plugins/sync-json.md +244 -0
  97. package/docs/id/plugins/sync-json.md +244 -0
  98. package/docs/it/plugins/sync-json.md +244 -0
  99. package/docs/ja/plugins/sync-json.md +244 -0
  100. package/docs/ko/plugins/sync-json.md +244 -0
  101. package/docs/pl/plugins/sync-json.md +244 -0
  102. package/docs/pt/plugins/sync-json.md +244 -0
  103. package/docs/ru/plugins/sync-json.md +244 -0
  104. package/docs/tr/plugins/sync-json.md +245 -0
  105. package/docs/vi/plugins/sync-json.md +244 -0
  106. package/docs/zh/plugins/sync-json.md +244 -0
  107. package/package.json +14 -14
@@ -1,327 +1,123 @@
1
1
  ---
2
2
  createdAt: 2025-01-02
3
- updatedAt: 2025-06-29
4
- title: Intlayer e react-intl
5
- description: Integre Intlayer com react-intl para um aplicativo React
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
- - Blogumentação
11
- - Next.js
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
- # Internationalização do React (i18n) com **react-intl** e Intlayer
24
+ # Como automatizar suas traduções JSON do react-intl usando Intlayer
20
25
 
21
- Este guia mostra como integrar **Intlayer** com **react-intl** para gerenciar traduções em uma aplicação React. Você declarará seu conteúdo traduzível com o Intlayer e, em seguida, consumirá essas mensagens com **react-intl**, uma biblioteca popular do ecossistema [FormatJS](https://formatjs.io/docs/react-intl).
26
+ ## O que é o Intlayer?
22
27
 
23
- ## Visão Geral
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
- - **Intlayer** permite que você armazene traduções em arquivos de declaração de conteúdo **de nível de componente** (JSON, JS, TS, etc.) dentro do seu projeto.
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
- Ao configurar o Intlayer para **exportar** traduções em um formato **compatível com react-intl**, você pode automaticamente **gerar** e **atualizar** os arquivos de mensagem que `<IntlProvider>` (do react-intl) requer.
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
- ## Por Que Usar Intlayer com react-intl?
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
- 1. **Declarações de Conteúdo por Componente**
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
- ```bash
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
- 2. **Traduções Centralizadas**
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
- 3. **Construção e Regeneração Automática**
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
- ## Instalação
50
+ ### Passo 1: Instalar dependências
55
51
 
56
- Em um projeto React típico, instale o seguinte:
52
+ Instale os pacotes necessários:
57
53
 
58
- ```bash
59
- # com npm
60
- npm install intlayer react-intl
54
+ ```bash packageManager="npm"
55
+ npm install intlayer @intlayer/sync-json-plugin
56
+ ```
61
57
 
62
- # com yarn
63
- yarn add intlayer react-intl
58
+ ```bash packageManager="pnpm"
59
+ pnpm add intlayer @intlayer/sync-json-plugin
60
+ ```
64
61
 
65
- # com pnpm
66
- pnpm add intlayer react-intl
62
+ ```bash packageManager="yarn"
63
+ yarn add intlayer @intlayer/sync-json-plugin
67
64
  ```
68
65
 
69
- ### Por Que Esses Pacotes?
66
+ **Descrição dos pacotes:**
70
67
 
71
- - **intlayer**: CLI e biblioteca principal que escaneia por declarações de conteúdo, as mescla e constrói saídas de dicionário.
72
- - **react-intl**: A biblioteca principal do FormatJS que fornece `<IntlProvider>`, `<FormattedMessage>`, `useIntl()` e outros princípios de internacionalização.
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
- > Se você ainda não tiver o React instalado, precisará dele também (`react` e `react-dom`).
71
+ ### Passo 2: Implemente o plugin Intlayer para encapsular o JSON
75
72
 
76
- ## Configurando o Intlayer para Exportar Mensagens do react-intl
73
+ Crie um arquivo de configuração do Intlayer para definir os seus locais suportados:
77
74
 
78
- Na raiz do seu projeto, crie **`intlayer.config.ts`** (ou `.js`, `.mjs`, `.cjs`) assim:
75
+ **Se você também quiser exportar dicionários JSON para react-intl**, adicione o plugin `syncJSON`:
79
76
 
80
- ```typescript title="intlayer.config.ts"
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
- content: {
90
- // Indica ao Intlayer para gerar arquivos de mensagens para o react-intl
91
- dictionaryOutput: ["react-intl"],
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
- ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
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
- Ambas as abordagens são válidas , escolha o estilo que melhor se adequa ao seu aplicativo.
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
- ## Atualizando ou Adicionando Novas Traduções
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
- 1. **Adicione ou modifique** o conteúdo em qualquer arquivo `*.content.*`.
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
- ## Integração com TypeScript (Opcional)
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
- Se você estiver usando TypeScript, o Intlayer pode **gerar definições de tipo** para suas traduções.
108
+ ## Configuração do Git
301
109
 
302
- - Certifique-se de que o `tsconfig.json` inclua sua pasta `types` (ou qualquer pasta de saída que o Intlayer gera) na matriz `"include"`.
110
+ É recomendado ignorar os arquivos gerados automaticamente pelo Intlayer:
303
111
 
304
- ```json5
305
- {
306
- "compilerOptions": {
307
- // ...
308
- },
309
- "include": ["src", "types"],
310
- }
112
+ ```plaintext fileName=".gitignore"
113
+ # Ignorar arquivos gerados pelo Intlayer
114
+ .intlayer
311
115
  ```
312
116
 
313
- Os tipos gerados podem ajudar a detectar traduções ausentes ou chaves inválidas em seus componentes React no tempo de compilação.
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
- É comum **excluir** os artefatos internos de construção do Intlayer do controle de versão. No seu `.gitignore`, adicione:
119
+ ### Extensão VS Code
320
120
 
321
- ```plaintext
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
- Dependendo do seu fluxo de trabalho, você pode também querer ignorar ou commitar os dicionários finais em `./react-intl/messages`. Se seu pipeline CI/CD os regenerar, você pode ignorá-los com segurança; caso contrário, comite-os se precisar deles para implantações em produção.
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-06-29
4
- title: Intlayer и i18next
5
- description: Интегрируйте Intlayer с i18next для оптимальной интернационализации. Сравните два фреймворка и узнайте, как настроить их вместе.
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
- # Интернационализация с Intlayer и i18next
28
+ # Как автоматизировать ваши JSON-переводы i18next с помощью Intlayer
23
29
 
24
- i18next - это open-source фреймворк интернационализации (i18n), разработанный для JavaScript-приложений. Он широко используется для управления переводами, локализацией и переключением языков в программных проектах. Однако у него есть некоторые ограничения, которые могут усложнить масштабируемость и разработку.
30
+ ## Что такое Intlayer?
25
31
 
26
- Intlayer - это другой фреймворк интернационализации, который устраняет эти ограничения, предлагая более гибкий подход к декларации и управлению контентом. Давайте рассмотрим некоторые ключевые отличия между i18next и Intlayer, и как настроить оба для оптимальной интернационализации.
32
+ **Intlayer** это инновационная, открытая библиотека для интернационализации, созданная для устранения недостатков традиционных решений i18n. Она предлагает современный подход к управлению контентом в JavaScript-приложениях.
27
33
 
28
- ## Intlayer против i18next: ключевые отличия
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
- ### 1. Декларация контента
36
+ ## Почему стоит сочетать Intlayer с i18next?
31
37
 
32
- С помощью i18next словари перевода должны быть объявлены в конкретной папке, что может усложнить масштабируемость приложения. В отличие от этого, Intlayer позволяет объявлять контент в той же директории, что и ваш компонент. Это имеет несколько преимуществ:
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
- - **Автоматическая адаптация**: Если компонент меняет местоположение или удаляется, Intlayer обнаруживает это и адаптируется автоматически.
40
+ 1. **Существующая кодовая база**: У вас уже есть реализованная система i18next, и вы хотите постепенно перейти на улучшенный опыт разработки с Intlayer.
41
+ 2. **Требования наследия**: Ваш проект требует совместимости с существующими плагинами или рабочими процессами i18next.
42
+ 3. **Знакомство команды**: Ваша команда привыкла к i18next, но хочет улучшить управление контентом.
36
43
 
37
- ### 2. Сложность конфигурации
44
+ **Для этого Intlayer может быть реализован как адаптер для i18next, чтобы помочь автоматизировать ваши JSON-переводы в CLI или CI/CD пайплайнах, тестировать переводы и многое другое.**
38
45
 
39
- Настройка i18next может быть сложной, особенно при интеграции с серверными компонентами или настройке middleware для таких фреймворков, как Next.js. Intlayer упрощает этот процесс, предлагая более простую настройку.
46
+ В этом руководстве показано, как использовать превосходную систему декларации контента Intlayer, сохраняя совместимость с i18next.
40
47
 
41
- ### 3. Согласованность переводов словарей
48
+ ## Содержание
42
49
 
43
- Обеспечение согласованности словарей перевода на разных языках может быть проблематичным с i18next. Эта несогласованность может привести к сбоям приложения, если не обрабатывать это должным образом. Intlayer решает эту проблему, вводя ограничения на переведенный контент, что гарантирует, что ни один перевод не будет пропущен, и что переведенный контент будет точным.
50
+ <TOC/>
44
51
 
45
- ### 4. Интеграция с TypeScript
52
+ ## Пошаговое руководство по настройке Intlayer с i18next
46
53
 
47
- Intlayer предлагает лучшую интеграцию с TypeScript, позволяя автоматически предлагать контент в вашем коде, тем самым повышая эффективность разработки.
54
+ ### Шаг 1: Установка зависимостей
48
55
 
49
- ### 5. Обмен контентом между приложениями
56
+ Установите необходимые пакеты:
50
57
 
51
- Intlayer облегчает обмен файлами декларации контента между несколькими приложениями и общими библиотеками. Эта функция упрощает поддержку согласованных переводов в более крупном кодовом базисе.
58
+ ```bash packageManager="npm"
59
+ npm install intlayer @intlayer/sync-json-plugin
60
+ ```
52
61
 
53
- ## Как сгенерировать словари i18next с Intlayer
62
+ ```bash packageManager="pnpm"
63
+ pnpm add intlayer @intlayer/sync-json-plugin
64
+ ```
54
65
 
55
- ### Настройка Intlayer для экспорта словарей i18next
66
+ ```bash packageManager="yarn"
67
+ yarn add intlayer @intlayer/sync-json-plugin
68
+ ```
56
69
 
57
- > Важные заметки
70
+ **Описание пакетов:**
58
71
 
59
- > Экспорт словарей i18next в настоящее время находится в бета-версии и не гарантирует совместимость 1: 1 с другими фреймворками. Рекомендуется придерживаться настройки, основанной на Intlayer, чтобы минимизировать проблемы.
72
+ - **intlayer**: Основная библиотека для управления интернационализацией, декларации контента и сборки
73
+ - **@intlayer/sync-json-plugin**: Плагин для экспорта деклараций контента Intlayer в JSON-формат, совместимый с i18next
60
74
 
61
- Чтобы экспортировать словари i18next, вам нужно соответствующим образом настроить Intlayer. Ниже приведен пример того, как настроить Intlayer для экспорта как словарей Intlayer, так и i18next.
75
+ ### Шаг 2: Реализация плагина Intlayer для обертки JSON
62
76
 
63
- ```typescript fileName="intlayer.config.ts" codeFormat="typescript"
64
- import { Locales, type IntlayerConfig } from "intlayer";
77
+ Создайте файл конфигурации Intlayer для определения поддерживаемых локалей:
65
78
 
66
- const config: IntlayerConfig = {
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
- export default config;
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
- /** @type {import('intlayer').IntlayerConfig} */
82
- const config = {
83
- content: {
84
- // Укажите, что Intlayer будет экспортировать как словари Intlayer, так и i18next
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
- ```javascript fileName="intlayer.config.cjs" codeFormat="commonjs"
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
- Включив 'i18next' в конфигурацию, Intlayer генерирует специальные словари i18next в дополнение к словарям Intlayer. Обратите внимание, что удаление 'intlayer' из конфигурации может нарушить совместимость с React-Intlayer или Next-Intlayer.
102
+ Если вы хотите, чтобы JSON сосуществовал с файлами декларации контента Intlayer (`.content` файлы), Intlayer будет работать следующим образом:
111
103
 
112
- ### Импортирование словарей в вашу конфигурацию i18next
104
+ 1. загрузит как JSON, так и файлы декларации контента и преобразует их в словарь Intlayer.
105
+ 2. если возникают конфликты между JSON и файлами декларации контента, Intlayer выполнит слияние всех словарей. В зависимости от приоритета плагинов и файла декларации контента (все настраивается).
113
106
 
114
- Чтобы импортировать сгенерированные словари в вашу конфигурацию i18next, вы можете использовать 'i18next-resources-to-backend'. Вот пример того, как импортировать ваши словари i18next:
107
+ Если изменения вносятся с помощью CLI для перевода JSON или через CMS, Intlayer обновит JSON-файл с новыми переводами.
115
108
 
116
- ```typescript fileName="i18n/client.ts" codeFormat="typescript"
117
- // i18n/client.ts
109
+ ## Конфигурация Git
118
110
 
119
- import i18next from "i18next";
120
- import resourcesToBackend from "i18next-resources-to-backend";
111
+ Рекомендуется игнорировать автоматически сгенерированные файлы Intlayer:
121
112
 
122
- i18next
123
- // Ваша конфигурация i18next
124
- .use(
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
- ```javascript fileName="i18n/client.mjs" codeFormat="esm"
133
- // i18n/client.mjs
134
-
135
- import i18next from "i18next";
136
- import resourcesToBackend from "i18next-resources-to-backend";
118
+ Эти файлы могут быть восстановлены во время процесса сборки и не требуют добавления в систему контроля версий.
137
119
 
138
- i18next
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
- ```javascript fileName="i18n/client.cjs" codeFormat="commonjs"
149
- // i18n/client.cjs
122
+ Для улучшения опыта разработчика установите официальное **расширение Intlayer для VS Code**:
150
123
 
151
- const i18next = require("i18next");
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)