@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,325 +1,122 @@
1
1
  ---
2
2
  createdAt: 2025-01-02
3
- updatedAt: 2025-06-29
4
- title: Intlayer y react-intl
5
- description: Integra Intlayer con react-intl para una aplicación React
3
+ updatedAt: 2025-10-29
4
+ title: Cómo automatizar tus traducciones JSON de react-intl usando Intlayer
5
+ description: Automatiza tus traducciones JSON con Intlayer y react-intl para una internacionalización mejorada en aplicaciones React.
6
6
  keywords:
7
7
  - react-intl
8
8
  - Intlayer
9
9
  - Internacionalización
10
- - Blogumentación
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: Cambio al plugin syncJSON
17
22
  ---
18
23
 
19
- # React Internationalization (i18n) with **react-intl** y Intlayer
24
+ # Cómo automatizar tus traducciones JSON de react-intl usando Intlayer
20
25
 
21
- Esta guía muestra cómo integrar **Intlayer** con **react-intl** para gestionar traducciones en una aplicación React. Declararás tu contenido traducible con Intlayer y luego consumirás esos mensajes con **react-intl**, una biblioteca popular del ecosistema [FormatJS](https://formatjs.io/docs/react-intl).
26
+ ## ¿Qué es Intlayer?
22
27
 
23
- ## Visión General
28
+ **Intlayer** es una biblioteca innovadora y de código abierto para la internacionalización, diseñada para abordar las limitaciones de las soluciones i18n tradicionales. Ofrece un enfoque moderno para la gestión de contenido en aplicaciones React.
24
29
 
25
- - **Intlayer** te permite almacenar traducciones en archivos de declaración de contenido a **nivel de componente** (JSON, JS, TS, etc.) dentro de tu proyecto.
26
- - **react-intl** proporciona componentes y hooks de React (como `<FormattedMessage>` y `useIntl()`) para mostrar cadenas localizadas.
30
+ Consulta una comparación concreta con react-intl en nuestro artículo del blog [react-i18next vs. react-intl vs. Intlayer](https://github.com/aymericzip/intlayer/blob/main/docs/blog/es/react-i18next_vs_react-intl_vs_intlayer.md).
27
31
 
28
- Al configurar Intlayer para **exportar** traducciones en un formato **compatible con react-intl**, puedes **generar** y **actualizar** automáticamente los archivos de mensajes que requiere `<IntlProvider>` (de react-intl).
32
+ ## ¿Por qué combinar Intlayer con react-intl?
29
33
 
30
- ---
34
+ Aunque Intlayer proporciona una excelente solución i18n independiente (consulta nuestra [guía de integración con React](https://github.com/aymericzip/intlayer/blob/main/docs/docs/es/intlayer_with_vite+react.md)), es posible que desees combinarlo con react-intl por varias razones:
31
35
 
32
- ## ¿Por qué usar Intlayer con react-intl?
36
+ 1. **Código existente**: Tienes una implementación establecida de react-intl y deseas migrar gradualmente a la mejorada experiencia de desarrollador de Intlayer.
37
+ 2. **Requisitos heredados**: Tu proyecto requiere compatibilidad con plugins o flujos de trabajo existentes de react-intl.
38
+ 3. **Familiaridad del equipo**: Tu equipo está cómodo con react-intl pero quiere una mejor gestión de contenido.
33
39
 
34
- 1. **Declaraciones de Contenido por Componente**
35
- Los archivos de declaración de contenido de Intlayer pueden vivir junto a tus componentes de React, evitando traducciones “huérfanas” si los componentes se mueven o se eliminan. Por ejemplo:
40
+ **Para ello, Intlayer puede implementarse como un adaptador para react-intl que ayude a automatizar tus traducciones JSON en CLI o pipelines CI/CD, probar tus traducciones y más.**
36
41
 
37
- ```bash
38
- .
39
- └── src
40
- └── components
41
- └── MyComponent
42
- ├── index.content.ts # Declaración de contenido de Intlayer
43
- └── index.tsx # Componente React
44
- ```
42
+ Esta guía te muestra cómo aprovechar el sistema superior de declaración de contenido de Intlayer mientras mantienes la compatibilidad con react-intl.
45
43
 
46
- 2. **Traducciones Centralizadas**
47
- Cada archivo de declaración de contenido recopila todas las traducciones necesarias para un componente. Esto es particularmente útil en proyectos de TypeScript: las traducciones faltantes se pueden detectar en **tiempo de compilación**.
44
+ ## Tabla de Contenidos
48
45
 
49
- 3. **Generación Automática y Regeneración**
50
- Siempre que agregues o actualices traducciones, Intlayer regenerará los archivos JSON de mensajes. Luego puedes pasarlos al `<IntlProvider>` de react-intl.
46
+ <TOC/>
51
47
 
52
- ---
48
+ ## Guía paso a paso para configurar Intlayer con react-intl
53
49
 
54
- ## Instalación
50
+ ### Paso 1: Instalar dependencias
55
51
 
56
- En un proyecto típico de React, instala lo siguiente:
52
+ Instala los paquetes necesarios:
57
53
 
58
- ```bash
59
- # con npm
60
- npm install intlayer react-intl
54
+ ```bash packageManager="npm"
55
+ npm install intlayer @intlayer/sync-json-plugin
56
+ ```
61
57
 
62
- # con yarn
63
- yarn add intlayer react-intl
58
+ ```bash packageManager="pnpm"
59
+ pnpm add intlayer @intlayer/sync-json-plugin
60
+ ```
64
61
 
65
- # con 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 qué estos paquetes?
66
+ **Descripción de los paquetes:**
70
67
 
71
- - **intlayer**: CLI y biblioteca principal que escanea las declaraciones de contenido, las fusiona y construye salidas de diccionario.
72
- - **react-intl**: La biblioteca principal de FormatJS que proporciona `<IntlProvider>`, `<FormattedMessage>`, `useIntl()` y otros elementos básicos de internacionalización.
68
+ - **intlayer**: Biblioteca principal para la gestión de internacionalización, declaración de contenido y construcción
69
+ - **@intlayer/sync-json-plugin**: Plugin para exportar declaraciones de contenido de Intlayer a un formato JSON compatible con react-intl
73
70
 
74
- > Si aún no tienes React instalado, también lo necesitarás (`react` y `react-dom`).
71
+ ### Paso 2: Implementar el plugin de Intlayer para envolver el JSON
75
72
 
76
- ## Configurando Intlayer para Exportar Mensajes react-intl
73
+ Crea un archivo de configuración de Intlayer para definir los locales que soportas:
77
74
 
78
- En la raíz de tu proyecto, crea **`intlayer.config.ts`** (o `.js`, `.mjs`, `.cjs`) de la siguiente manera:
75
+ **Si también quieres exportar diccionarios JSON para react-intl**, añade el 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
- // Agrega tantas locales como desees
86
83
  locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],
87
84
  defaultLocale: Locales.ENGLISH,
88
85
  },
89
- content: {
90
- // Indica a Intlayer que genere archivos de mensajes para react-intl
91
- dictionaryOutput: ["react-intl"],
92
-
93
- // El directorio donde Intlayer escribirá tus archivos JSON de mensajes
94
- reactIntlMessagesDir: "./react-intl/messages",
95
- },
96
- };
97
-
98
- export default config;
99
- ```
100
-
101
- > **Nota**: Para otras extensiones de archivo (`.mjs`, `.cjs`, `.js`), consulta la [documentación de Intlayer](https://intlayer.org/es/doc/concept/configuration) para detalles de uso.
102
-
103
- ---
104
-
105
- ## Creando Tus Declaraciones de Contenido de Intlayer
106
-
107
- Intlayer escanea tu base de código (por defecto, bajo `./src`) en busca de archivos que coincidan con `*.content.{ts,tsx,js,jsx,mjs,mjx,cjs,cjx,json}`.
108
- Aquí hay un ejemplo 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 convierte en la clave de mensaje de nivel superior en tu archivo JSON de react-intl
115
- key: "my-component",
116
-
117
- content: {
118
- // Cada llamada a t() declara un campo traducible
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
- Si prefieres JSON o diferentes sabores de JS (`.cjs`, `.mjs`), la estructura es en gran medida la misma, consulta [documentación de Intlayer sobre declaración de contenido](https://intlayer.org/es/doc/concept/content).
136
-
137
- ---
138
-
139
- ## Construyendo los Mensajes de react-intl
140
-
141
- Para generar los archivos JSON de mensajes reales para **react-intl**, ejecuta:
142
-
143
- ```bash
144
- # con npm
145
- npx intlayer dictionaries build
146
-
147
- # con yarn
148
- yarn intlayer build
149
-
150
- # con pnpm
151
- pnpm intlayer build
152
- ```
153
-
154
- Esto escanea todos los archivos `*.content.*`, los compila y escribe los resultados en el directorio especificado en tu **`intlayer.config.ts`** , en este ejemplo, `./react-intl/messages`.
155
- Una salida típica podría verse así:
156
-
157
- ```bash
158
- .
159
- └── react-intl
160
- └── messages
161
- ├── en.json
162
- ├── fr.json
163
- └── es.json
164
- ```
165
-
166
- Cada archivo es un objeto JSON cuyas **claves de nivel superior** corresponden a cada **`content.key`** de tus declaraciones. Las **sub-claves** (como `helloWorld`) reflejan las traducciones declaradas dentro de ese ítem de contenido.
167
-
168
- Por ejemplo, el **en.json** podría verse así:
169
-
170
- ```json fileName="react-intl/messages/en/my-component.json"
171
- {
172
- "helloWorld": "Hello World",
173
- "description": "This is a description"
174
- }
175
- ```
176
-
177
- ---
178
-
179
- ## Inicializando react-intl en Tu Aplicación React
180
-
181
- ### 1. Cargar los Mensajes Generados
182
-
183
- Donde configuras el componente raíz de tu aplicación (por ejemplo, `src/main.tsx` o `src/index.tsx`), deberás:
184
-
185
- 1. **Importar** los archivos de mensajes generados (ya sea de forma estática o dinámica).
186
- 2. **Proveer** estos a `<IntlProvider>` de `react-intl`.
187
-
188
- Un enfoque simple es importarlos **estáticamente**:
189
-
190
- ```typescript title="src/index.tsx"
191
- import React from "react";
192
- import ReactDOM from "react-dom/client";
193
- import { IntlProvider } from "react-intl";
194
- import App from "./App";
195
-
196
- // Importa los archivos JSON de la salida de construcción.
197
- // Alternativamente, puedes importar dinámicamente según la elección de idioma del usuario.
198
- import en from "../react-intl/messages/en.json";
199
- import fr from "../react-intl/messages/fr.json";
200
- import es from "../react-intl/messages/es.json";
201
-
202
- // Si tienes un mecanismo para detectar el idioma del usuario, configúralo aquí.
203
- // Para simplicidad, elijamos inglés.
204
- const locale = "en";
205
-
206
- // Reúne los mensajes en un objeto (o escógelos dinámicamente)
207
- const messagesRecord: Record<string, Record<string, any>> = {
208
- en,
209
- fr,
210
- es,
90
+ ],
211
91
  };
212
92
 
213
- ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
214
- <React.StrictMode>
215
- <IntlProvider locale={locale} messages={messagesRecord[locale]}>
216
- <App />
217
- </IntlProvider>
218
- </React.StrictMode>
219
- );
220
- ```
221
-
222
- > **Consejo**: Para proyectos reales, podrías:
223
- >
224
- > - Cargar dinámicamente los mensajes JSON en tiempo de ejecución.
225
- > - Usar detección de local basado en el entorno, navegador o cuenta de usuario.
226
-
227
- ### 2. Usar `<FormattedMessage>` o `useIntl()`
228
-
229
- Una vez que tus mensajes están cargados en `<IntlProvider>`, cualquier componente hijo puede usar react-intl para acceder a cadenas localizadas. Hay dos enfoques principales:
230
-
231
- - **Componente `<FormattedMessage>`**
232
- - **Hook `useIntl()`**
233
-
234
- ---
235
-
236
- ## Usando Traducciones en Componentes React
237
-
238
- ### Enfoque A: `<FormattedMessage>`
239
-
240
- Para un uso rápido en línea:
241
-
242
- ```tsx title="src/components/MyComponent/index.tsx"
243
- import React from "react";
244
- import { FormattedMessage } from "react-intl";
245
-
246
- export default function MyComponent() {
247
- return (
248
- <div>
249
- <h1>
250
- {/* “my-component.helloWorld” se refiere a la clave de en.json, fr.json, etc. */}
251
- <FormattedMessage id="my-component.helloWorld" />
252
- </h1>
253
-
254
- <p>
255
- <FormattedMessage id="my-component.description" />
256
- </p>
257
- </div>
258
- );
259
- }
260
- ```
261
-
262
- > La prop **`id`** en `<FormattedMessage>` debe coincidir con la **clave de nivel superior** (`my-component`) más cualquier sub-clave (`helloWorld`).
263
-
264
- ### Enfoque B: `useIntl()`
265
-
266
- Para un uso más dinámico:
267
-
268
- ```tsx title="src/components/MyComponent/index.tsx"
269
- import React from "react";
270
- import { useIntl } from "react-intl";
271
-
272
- export default function MyComponent() {
273
- const intl = useIntl();
274
-
275
- return (
276
- <div>
277
- <h1>{intl.formatMessage({ id: "my-component.helloWorld" })}</h1>
278
- <p>{intl.formatMessage({ id: "my-component.description" })}</p>
279
- </div>
280
- );
281
- }
93
+ export default config;
282
94
  ```
283
95
 
284
- Cualquiera de los enfoques es válido: elige el estilo que mejor se adapte a tu aplicación.
285
-
286
- ---
96
+ El plugin `syncJSON` envolverá automáticamente el JSON. Leerá y escribirá los archivos JSON sin cambiar la arquitectura del contenido.
287
97
 
288
- ## Actualizando o Agregando Nuevas Traducciones
98
+ Si deseas hacer coexistir ese JSON con los archivos de declaración de contenido de Intlayer (`.content`), Intlayer procederá de la siguiente manera:
289
99
 
290
- 1. **Agrega o modifica** contenido en cualquier archivo `*.content.*`.
291
- 2. Vuelve a ejecutar `intlayer build` para regenerar los archivos JSON en `./react-intl/messages`.
292
- 3. React (y react-intl) detectarán las actualizaciones la próxima vez que reconstruyas o recargues tu aplicación.
100
+ 1. cargar tanto los archivos JSON como los archivos de declaración de contenido y transformarlos en un diccionario de Intlayer.
101
+ 2. si hay conflictos entre los archivos JSON y los archivos de declaración de contenido, Intlayer procederá a fusionar todos esos diccionarios. Dependiendo de la prioridad de los plugins y la del archivo de declaración de contenido (todos son configurables).
293
102
 
294
- ---
103
+ Si se realizan cambios usando la CLI para traducir el JSON, o usando el CMS, Intlayer actualizará el archivo JSON con las nuevas traducciones.
295
104
 
296
- ## Integración con TypeScript (Opcional)
105
+ Para ver más detalles sobre el plugin `syncJSON`, por favor consulte la [documentación del plugin syncJSON](https://github.com/aymericzip/intlayer/blob/main/docs/docs/es/plugins/sync-json.md).
297
106
 
298
- Si estás usando TypeScript, Intlayer puede **generar definiciones de tipo** para tus traducciones.
107
+ ## Configuración de Git
299
108
 
300
- - Asegúrate de que `tsconfig.json` incluya tu carpeta `types` (o cualquier carpeta de salida que genere Intlayer) en el arreglo `"include"`.
109
+ Se recomienda ignorar los archivos generados automáticamente por Intlayer:
301
110
 
302
- ```json5
303
- {
304
- "compilerOptions": {
305
- // ...
306
- },
307
- "include": ["src", "types"],
308
- }
111
+ ```plaintext fileName=".gitignore"
112
+ # Ignorar archivos generados por Intlayer
113
+ .intlayer
309
114
  ```
310
115
 
311
- Los tipos generados pueden ayudar a detectar traducciones faltantes o claves inválidas en tus componentes de React en tiempo de compilación.
312
-
313
- ---
314
-
315
- ## Configuración de Git
116
+ Estos archivos pueden ser regenerados durante su proceso de compilación y no necesitan ser comprometidos en el control de versiones.
316
117
 
317
- Es común **excluir** los artefactos de construcción internos de Intlayer del control de versiones. En tu `.gitignore`, añade:
118
+ ### Extensión de VS Code
318
119
 
319
- ```plaintext
320
- # Ignorar artefactos de construcción de intlayer
321
- .intlayer
322
- react-intl
323
- ```
120
+ Para mejorar la experiencia del desarrollador, instale la **Extensión oficial de Intlayer para VS Code**:
324
121
 
325
- Dependiendo de tu flujo de trabajo, también puede que desees ignorar o confirmar los diccionarios finales en `./react-intl/messages`. Si tu canal de CI/CD los regenera, puedes ignorarlos de forma segura; de lo contrario, confírmales si los necesitas para las implementaciones de producción.
122
+ [Instalar desde el Marketplace de VS Code](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 et i18next
5
- description: Intégrez Intlayer avec i18next pour une internationalisation optimale. Comparez les deux frameworks et apprenez à les configurer ensemble.
3
+ updatedAt: 2025-10-29
4
+ title: Comment automatiser vos traductions JSON i18next avec Intlayer
5
+ description: Automatisez vos traductions JSON avec Intlayer et i18next pour une internationalisation améliorée dans les applications 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
+ - Migration
18
+ - Intégration
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: Passage au plugin syncJSON
20
26
  ---
21
27
 
22
- # Internationalization with Intlayer and i18next
28
+ # Comment automatiser vos traductions JSON i18next avec Intlayer
23
29
 
24
- i18next est un framework open-source d'internationalisation (i18n) conçu pour les applications JavaScript. Il est largement utilisé pour gérer les traductions, la localisation et le changement de langue dans les projets logiciels. Cependant, il a certaines limites qui peuvent compliquer l'évolutivité et le développement.
30
+ ## Qu'est-ce que Intlayer ?
25
31
 
26
- Intlayer est un autre framework d'internationalisation qui répond à ces limitations, offrant une approche plus flexible pour la déclaration et la gestion du contenu. Explorons quelques différences clés entre i18next et Intlayer, et comment configurer les deux pour une internationalisation optimale.
32
+ **Intlayer** est une bibliothèque dinternationalisation innovante et open-source conçue pour pallier les limites des solutions i18n traditionnelles. Elle offre une approche moderne de la gestion de contenu dans les applications JavaScript.
27
33
 
28
- ## Intlayer vs. i18next: Différences Clés
34
+ Consultez une comparaison concrète avec i18next dans notre article de blog [next-i18next vs. next-intl vs. Intlayer](https://github.com/aymericzip/intlayer/blob/main/docs/blog/fr/next-i18next_vs_next-intl_vs_intlayer.md).
29
35
 
30
- ### 1. Déclaration du Contenu
36
+ ## Pourquoi combiner Intlayer avec i18next ?
31
37
 
32
- Avec i18next, les dictionnaires de traduction doivent être déclarés dans un dossier spécifique, ce qui peut compliquer l'évolutivité de l'application. En revanche, Intlayer permet de déclarer le contenu dans le même répertoire que votre composant. Cela présente plusieurs avantages :
38
+ Bien qu’Intlayer fournisse une excellente solution i18n autonome (voir notre [guide d’intégration Next.js](https://github.com/aymericzip/intlayer/blob/main/docs/docs/fr/intlayer_with_nextjs_16.md)), vous pourriez vouloir le combiner avec i18next pour plusieurs raisons :
33
39
 
34
- - **Édition de Contenu Simplifiée**: Les utilisateurs n'ont pas à chercher le bon dictionnaire à éditer, réduisant ainsi le risque d'erreurs.
35
- - **Adaptation Automatique**: Si un composant change de localisation ou est supprimé, Intlayer le détecte et s'adapte automatiquement.
40
+ 1. **Base de code existante** : Vous disposez d’une implémentation i18next établie et souhaitez migrer progressivement vers la meilleure expérience développeur d’Intlayer.
41
+ 2. **Contraintes héritées** : Votre projet nécessite une compatibilité avec des plugins ou des workflows i18next existants.
42
+ 3. **Familiarité de l’équipe** : Votre équipe est à l’aise avec i18next mais souhaite une meilleure gestion du contenu.
36
43
 
37
- ### 2. Complexité de Configuration
44
+ **Pour cela, Intlayer peut être implémenté comme un adaptateur pour i18next afin d’automatiser vos traductions JSON dans les pipelines CLI ou CI/CD, tester vos traductions, et plus encore.**
38
45
 
39
- Configurer i18next peut être complexe, surtout lors de l'intégration avec des composants côté serveur ou la configuration de middleware pour des frameworks comme Next.js. Intlayer simplifie ce processus, offrant une configuration plus directe.
46
+ Ce guide vous montre comment tirer parti du système supérieur de déclaration de contenu d’Intlayer tout en maintenant la compatibilité avec i18next.
40
47
 
41
- ### 3. Cohérence des Dictionnaires de Traduction
48
+ ## Table des matières
42
49
 
43
- Assurer la cohérence des dictionnaires de traduction à travers différentes langues peut être difficile avec i18next. Cette incohérence peut entraîner des plantages d'application si elle n'est pas correctement gérée. Intlayer y remédie en imposant des contraintes sur le contenu traduit, garantissant qu'aucune traduction ne soit manquée et que le contenu traduit soit précis.
50
+ <TOC/>
44
51
 
45
- ### 4. Intégration TypeScript
52
+ ## Guide étape par étape pour configurer Intlayer avec i18next
46
53
 
47
- Intlayer offre une meilleure intégration avec TypeScript, permettant des auto-suggestions de contenu dans votre code, améliorant ainsi l'efficacité du développement.
54
+ ### Étape 1 : Installer les dépendances
48
55
 
49
- ### 5. Partage de Contenu Entre Applications
56
+ Installez les paquets nécessaires :
50
57
 
51
- Intlayer facilite le partage de fichiers de déclaration de contenu entre plusieurs applications et bibliothèques partagées. Cette fonctionnalité rend plus facile le maintien de traductions cohérentes à travers une base de code plus large.
58
+ ```bash packageManager="npm"
59
+ npm install intlayer @intlayer/sync-json-plugin
60
+ ```
52
61
 
53
- ## Comment Générer des Dictionnaires i18next avec Intlayer
62
+ ```bash packageManager="pnpm"
63
+ pnpm add intlayer @intlayer/sync-json-plugin
64
+ ```
54
65
 
55
- ### Configurer Intlayer pour Exporter des Dictionnaires i18next
66
+ ```bash packageManager="yarn"
67
+ yarn add intlayer @intlayer/sync-json-plugin
68
+ ```
56
69
 
57
- > Notes Importantes
70
+ **Descriptions des paquets :**
58
71
 
59
- > L'exportation des dictionnaires i18next est actuellement en beta et ne garantit pas une compatibilité 1: 1 avec d'autres frameworks. Il est recommandé de s'en tenir à une configuration basée sur Intlayer pour minimiser les problèmes.
72
+ - **intlayer** : Bibliothèque principale pour la gestion de l'internationalisation, la déclaration de contenu et la construction
73
+ - **@intlayer/sync-json-plugin** : Plugin pour exporter les déclarations de contenu Intlayer au format JSON compatible i18next
60
74
 
61
- Pour exporter des dictionnaires i18next, vous devez configurer Intlayer de manière appropriée. Voici un exemple de la façon de configurer Intlayer pour exporter à la fois les dictionnaires Intlayer et i18next.
75
+ ### Étape 2 : Implémenter le plugin Intlayer pour envelopper le JSON
62
76
 
63
- ```typescript fileName="intlayer.config.ts" codeFormat="typescript"
64
- import { Locales, type IntlayerConfig } from "intlayer";
77
+ Créez un fichier de configuration Intlayer pour définir vos locales supportées :
65
78
 
66
- const config: IntlayerConfig = {
67
- content: {
68
- // Indiquez qu'Intlayer exportera à la fois les dictionnaires Intlayer et i18next
69
- dictionaryOutput: ["intlayer", "i18next"],
70
- // Chemin relatif depuis la racine du projet vers le répertoire où les dictionnaires i18n seront exportés
71
- i18nextResourcesDir: "./i18next/dictionaries",
72
- },
73
- };
79
+ **Si vous souhaitez également exporter des dictionnaires JSON pour i18next**, ajoutez le plugin `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
- // Indiquez qu'Intlayer exportera à la fois les dictionnaires Intlayer et i18next
85
- dictionaryOutput: ["intlayer", "i18next"],
86
- // Chemin relatif depuis la racine du projet vers le répertoire où les dictionnaires i18n seront exportés
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
- // Indiquez qu'Intlayer exportera à la fois les dictionnaires Intlayer et i18next
101
- dictionaryOutput: ["intlayer", "i18next"],
102
- // Chemin relatif depuis la racine du projet vers le répertoire où les dictionnaires i18n seront exportés
103
- i18nextResourcesDir: "./i18next/dictionaries",
104
- },
105
- };
106
-
107
- module.exports = config;
108
- ```
100
+ Le plugin `syncJSON` enveloppera automatiquement le JSON. Il lira et écrira les fichiers JSON sans modifier l'architecture du contenu.
109
101
 
110
- En incluant 'i18next' dans la configuration, Intlayer génère des dictionnaires i18next dédiés en plus des dictionnaires Intlayer. Notez que le fait de retirer 'intlayer' de la configuration peut provoquer des problèmes de compatibilité avec React-Intlayer ou Next-Intlayer.
102
+ Si vous souhaitez faire coexister ce JSON avec les fichiers de déclaration de contenu intlayer (`.content`), Intlayer procédera de la manière suivante :
111
103
 
112
- ### Importer des Dictionnaires dans Votre Configuration i18next
104
+ 1. charger à la fois les fichiers JSON et les fichiers de déclaration de contenu et les transformer en un dictionnaire intlayer.
105
+ 2. s'il y a des conflits entre les fichiers JSON et les fichiers de déclaration de contenu, Intlayer procédera à la fusion de tous ces dictionnaires. Cela dépendra de la priorité des plugins, ainsi que de celle du fichier de déclaration de contenu (tout est configurable).
113
106
 
114
- Pour importer les dictionnaires générés dans votre configuration i18next, vous pouvez utiliser 'i18next-resources-to-backend'. Voici un exemple de la façon d'importer vos dictionnaires i18next :
107
+ Si des modifications sont effectuées via la CLI pour traduire le JSON, ou en utilisant le CMS, Intlayer mettra à jour le fichier JSON avec les nouvelles traductions.
115
108
 
116
- ```typescript fileName="i18n/client.ts" codeFormat="typescript"
117
- // i18n/client.ts
109
+ ## Configuration Git
118
110
 
119
- import i18next from "i18next";
120
- import resourcesToBackend from "i18next-resources-to-backend";
111
+ Il est recommandé d'ignorer les fichiers Intlayer générés automatiquement :
121
112
 
122
- i18next
123
- // Votre configuration i18next
124
- .use(
125
- resourcesToBackend(
126
- (language: string, namespace: string) =>
127
- import(`../i18next/dictionaries/${language}/${namespace}.json`)
128
- )
129
- );
113
+ ```plaintext fileName=".gitignore"
114
+ # Ignorer les fichiers générés par 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
+ Ces fichiers peuvent être régénérés lors de votre processus de build et n'ont pas besoin d'être commités dans le contrôle de version.
137
119
 
138
- i18next
139
- // Votre configuration i18next
140
- .use(
141
- resourcesToBackend(
142
- (language, namespace) =>
143
- import(`../i18next/dictionaries/${language}/${namespace}.json`)
144
- )
145
- );
146
- ```
120
+ ### Extension VS Code
147
121
 
148
- ```javascript fileName="i18n/client.cjs" codeFormat="commonjs"
149
- // i18n/client.cjs
122
+ Pour une meilleure expérience développeur, installez l'extension officielle **Intlayer VS Code Extension** :
150
123
 
151
- const i18next = require("i18next");
152
- const resourcesToBackend = require("i18next-resources-to-backend");
153
-
154
- i18next
155
- // Votre configuration i18next
156
- .use(
157
- resourcesToBackend(
158
- (language, namespace) =>
159
- import(`../i18next/dictionaries/${language}/${namespace}.json`)
160
- )
161
- );
162
- ```
124
+ [Installer depuis le Marketplace VS Code](https://marketplace.visualstudio.com/items?itemName=intlayer.intlayer-vs-code-extension)