@intlayer/docs 7.3.0-canary.0 → 7.3.1

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 (53) hide show
  1. package/dist/cjs/generated/docs.entry.cjs +19 -0
  2. package/dist/cjs/generated/docs.entry.cjs.map +1 -1
  3. package/dist/esm/generated/docs.entry.mjs +19 -0
  4. package/dist/esm/generated/docs.entry.mjs.map +1 -1
  5. package/dist/types/generated/docs.entry.d.ts +1 -0
  6. package/dist/types/generated/docs.entry.d.ts.map +1 -1
  7. package/docs/ar/bundle_optimization.md +180 -0
  8. package/docs/ar/vs_code_extension.md +4 -0
  9. package/docs/de/bundle_optimization.md +190 -0
  10. package/docs/de/how_works_intlayer.md +1 -1
  11. package/docs/de/vs_code_extension.md +4 -0
  12. package/docs/en/bundle_optimization.md +180 -0
  13. package/docs/en/configuration.md +5 -2
  14. package/docs/en/how_works_intlayer.md +1 -1
  15. package/docs/en/vs_code_extension.md +7 -0
  16. package/docs/en-GB/bundle_optimization.md +180 -0
  17. package/docs/en-GB/how_works_intlayer.md +1 -1
  18. package/docs/en-GB/vs_code_extension.md +4 -0
  19. package/docs/es/bundle_optimization.md +190 -0
  20. package/docs/es/how_works_intlayer.md +1 -1
  21. package/docs/es/vs_code_extension.md +4 -0
  22. package/docs/fr/bundle_optimization.md +180 -0
  23. package/docs/fr/how_works_intlayer.md +1 -1
  24. package/docs/fr/vs_code_extension.md +4 -0
  25. package/docs/hi/bundle_optimization.md +180 -0
  26. package/docs/hi/vs_code_extension.md +4 -0
  27. package/docs/id/bundle_optimization.md +180 -0
  28. package/docs/id/how_works_intlayer.md +1 -1
  29. package/docs/id/vs_code_extension.md +4 -0
  30. package/docs/it/bundle_optimization.md +180 -0
  31. package/docs/it/how_works_intlayer.md +1 -1
  32. package/docs/it/vs_code_extension.md +4 -0
  33. package/docs/ja/bundle_optimization.md +180 -0
  34. package/docs/ja/vs_code_extension.md +4 -0
  35. package/docs/ko/bundle_optimization.md +180 -0
  36. package/docs/ko/vs_code_extension.md +4 -0
  37. package/docs/pl/bundle_optimization.md +180 -0
  38. package/docs/pl/how_works_intlayer.md +1 -1
  39. package/docs/pl/vs_code_extension.md +4 -0
  40. package/docs/pt/bundle_optimization.md +180 -0
  41. package/docs/pt/how_works_intlayer.md +1 -1
  42. package/docs/pt/vs_code_extension.md +4 -0
  43. package/docs/ru/bundle_optimization.md +180 -0
  44. package/docs/ru/vs_code_extension.md +4 -0
  45. package/docs/tr/bundle_optimization.md +180 -0
  46. package/docs/tr/how_works_intlayer.md +1 -1
  47. package/docs/tr/vs_code_extension.md +4 -0
  48. package/docs/vi/bundle_optimization.md +180 -0
  49. package/docs/vi/vs_code_extension.md +4 -0
  50. package/docs/zh/bundle_optimization.md +180 -0
  51. package/docs/zh/vs_code_extension.md +4 -0
  52. package/package.json +8 -8
  53. package/src/generated/docs.entry.ts +19 -0
@@ -654,6 +654,8 @@ Intlayer supports multiple AI providers for enhanced flexibility and choice. Cur
654
654
  - _Default_: None
655
655
  - _Description_: Provides additional context about your application to the AI model, helping it generate more accurate and contextually appropriate translations. This can include information about your app's domain, target audience, tone, or specific terminology.
656
656
 
657
+ > If you provide additional parameters, Intlayer will pass them to the AI model as context. It can be used to customize the reasoning effort, text verbosity, etc
658
+
657
659
  ### Build Configuration
658
660
 
659
661
  Settings that control how Intlayer optimizes and builds your application's internationalization.
@@ -668,9 +670,10 @@ Build options apply to the `@intlayer/babel` and `@intlayer/swc` plugins.
668
670
 
669
671
  - **optimize**:
670
672
  - _Type_: `boolean`
671
- - _Default_: `process.env.NODE_ENV === 'production'`
673
+ - _Default_: `undefined`
672
674
  - _Description_: Controls whether the build should be optimized.
673
- - _Example_: `true`
675
+ - _Example_: `process.env.NODE_ENV === 'production'`
676
+ - _Note_: By default, the build optimization is not fixed. If not set, Intlayer will trigger the build optimization on the build of your application (vite / nextjs / etc). Setting it to `true` will force the build optimization, including during dev mode. Setting it to `false` will disable the build optimization.
674
677
  - _Note_: When enabled, Intlayer will replace all calls of dictionaries to optimize chunking. That way the final bundle will import only the dictionaries that are used. All imports will stay as static import to avoid async processing when loading the dictionaries.
675
678
  - _Note_: Intlayer will replace all calls of `useIntlayer` with the defined mode by the `importMode` option and `getIntlayer` with `getDictionary`.
676
679
  - _Note_: This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.
@@ -146,7 +146,7 @@ The `vue-intlayer` package is used to interpret Intlayer dictionaries and make t
146
146
 
147
147
  The `nuxt-intlayer` package is as Nuxt module to make Intlayer dictionaries usable in Nuxt applications. It integrates essential features to make Intlayer work in a Nuxt environment, such as translation middleware, routing, or the `nuxt.config.js` file configuration.
148
148
 
149
- ### svelte-intlayer (WIP)
149
+ ### svelte-intlayer
150
150
 
151
151
  The `svelte-intlayer` package is used to interpret Intlayer dictionaries and make them usable in Svelte applications.
152
152
 
@@ -16,6 +16,9 @@ slugs:
16
16
  - doc
17
17
  - vs-code-extension
18
18
  history:
19
+ - version: 7.3.0
20
+ date: 2025-11-25
21
+ changes: Add extract content command
19
22
  - version: 6.1.5
20
23
  date: 2025-09-30
21
24
  changes: Add demo gif
@@ -42,6 +45,10 @@ Extension link: [https://marketplace.visualstudio.com/items?itemName=Intlayer.in
42
45
 
43
46
  ## Features
44
47
 
48
+ ![Extract content](https://github.com/aymericzip/intlayer-vs-code-extension/blob/master/assets/vscode_extention_extract_content.gif?raw=true)
49
+
50
+ - **Extract Content** – Extract content from your React / Vue / Svelte components
51
+
45
52
  ![Fill dictionaries](https://github.com/aymericzip/intlayer-vs-code-extension/blob/master/assets/vscode_extention_fill_active_dictionary.gif?raw=true)
46
53
 
47
54
  - **Instant Navigation** – Quickly jump to the correct content file when clicking on a `useIntlayer` key.
@@ -0,0 +1,180 @@
1
+ ---
2
+ createdAt: 2025-11-25
3
+ updatedAt: 2025-11-25
4
+ title: Optimising i18n Bundle Size & Performance
5
+ description: Reduce application bundle size by optimising internationalisation (i18n) content. Learn how to leverage tree shaking and lazy loading for dictionaries with Intlayer.
6
+ keywords:
7
+ - Bundle Optimisation
8
+ - Content Automation
9
+ - Dynamic Content
10
+ - Intlayer
11
+ - Next.js
12
+ - JavaScript
13
+ - React
14
+ slugs:
15
+ - doc
16
+ - concept
17
+ - bundle-optimization
18
+ history:
19
+ - version: 6.0.0
20
+ date: 2025-11-25
21
+ changes: Init history
22
+ ---
23
+
24
+ # Optimising i18n Bundle Size & Performance
25
+
26
+ One of the most common challenges with traditional i18n solutions relying on JSON files is managing content size. If developers do not manually separate content into namespaces, users often end up downloading translations for every page and potentially every language just to view a single page.
27
+
28
+ For example, an application with 10 pages translated into 10 languages might result in a user downloading the content of 100 pages, even though they only need **one** (the current page in the current language). This leads to wasted bandwidth and slower load times.
29
+
30
+ > To detect this, you can use bundle analysers such as `rollup-plugin-visualizer` (vite), `@next/bundle-analyser` (next.js), or `webpack-bundle-analyser` (React CRA / Angular / etc).
31
+
32
+ **Intlayer solves this problem through build-time optimisation.** It analyses your code to detect which dictionaries are actually used per component and reinjects only the necessary content into your bundle.
33
+
34
+ ## Table of Contents
35
+
36
+ <TOC />
37
+
38
+ ## How It Works
39
+
40
+ Intlayer uses a **per-component approach**. Unlike global JSON files, your content is defined alongside or within your components. During the build process, Intlayer:
41
+
42
+ 1. **Analyses** your code to find `useIntlayer` calls.
43
+ 2. **Builds** the corresponding dictionary content.
44
+ 3. **Replaces** the `useIntlayer` call with optimised code based on your configuration.
45
+
46
+ This ensures that:
47
+
48
+ - If a component is not imported, its content is not included in the bundle (Dead Code Elimination).
49
+ - If a component is lazy-loaded, its content is also lazy-loaded.
50
+
51
+ ## Setup by Platform
52
+
53
+ ### Next.js
54
+
55
+ Next.js requires the `@intlayer/swc` plugin to handle the transformation, as Next.js uses SWC for builds.
56
+
57
+ > This plugin is installed by default because SWC plugins are still experimental for Next.js. It may change in the future.
58
+
59
+ ### Vite
60
+
61
+ Vite uses the `@intlayer/babel` plugin which is included as a dependency of `vite-intlayer`. The optimisation is enabled by default.
62
+
63
+ ### Webpack
64
+
65
+ To enable bundle optimisation with Intlayer on Webpack, you need to install and configure the appropriate Babel (`@intlayer/babel`) or SWC (`@intlayer/swc`) plugin.
66
+
67
+ ### Expo / Lynx
68
+
69
+ Bundle optimisation is **not available yet** for this platform. Support will be added in a future release.
70
+
71
+ ## Configuration
72
+
73
+ You can control how Intlayer optimises your bundle via the `build` property in your `intlayer.config.ts`.
74
+
75
+ ```typescript fileName="intlayer.config.ts"
76
+ import { Locales, type IntlayerConfig } from "intlayer";
77
+
78
+ const config: IntlayerConfig = {
79
+ internationalization: {
80
+ locales: [Locales.ENGLISH, Locales.FRENCH],
81
+ defaultLocale: Locales.ENGLISH,
82
+ },
83
+ build: {
84
+ optimize: true,
85
+ importMode: "static", // or 'dynamic'
86
+ traversePattern: ["**/*.{js,ts,mjs,cjs,jsx,tsx}", "!**/node_modules/**"],
87
+ },
88
+ };
89
+
90
+ export default config;
91
+ ```
92
+
93
+ > Keeping the default option for `optimize` is recommended in the vast majority of cases.
94
+
95
+ > See doc configuration for more details: [Configuration](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en-GB/configuration.md)
96
+
97
+ ### Build Options
98
+
99
+ The following options are available under the `build` configuration object:
100
+
101
+ | Property | Type | Default | Description |
102
+ | :-------------------- | :------------------------------ | :------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
103
+ | **`optimize`** | `boolean` | `undefined` | Controls whether build optimisation is enabled. If `true`, Intlayer replaces dictionary calls with optimised injects. If `false`, optimisation is disabled. Ideally set to `true` in production. |
104
+ | **`importMode`** | `'static' , 'dynamic' , 'live'` | `'static'` | Determines how dictionaries are loaded (see details below). |
105
+ | **`traversePattern`** | `string[]` | `['**/*.{js,ts,jsx,tsx}', ...]` | Glob patterns defining which files Intlayer should scan for optimisation. Use this to exclude unrelated files and speed up builds. |
106
+ | **`outputFormat`** | `'esm', 'cjs'` | `'esm', 'cjs'` | Controls the output format of the built dictionaries. |
107
+
108
+ ## Import Modes
109
+
110
+ The `importMode` setting dictates how the dictionary content is injected into your component.
111
+
112
+ ### 1. Static Mode (`default`)
113
+
114
+ In static mode, Intlayer replaces `useIntlayer` with `useDictionary` and injects the dictionary directly into the JavaScript bundle.
115
+
116
+ - **Pros:** Instant rendering (synchronous), zero extra network requests during hydration.
117
+ - **Cons:** The bundle includes translations for **all** available languages for that specific component.
118
+ - **Best for:** Single Page Applications (SPA).
119
+
120
+ **Transformed Code Example:**
121
+
122
+ ```tsx
123
+ // Your code
124
+ const content = useIntlayer("my-key");
125
+
126
+ // Optimised code (Static)
127
+ const content = useDictionary({
128
+ key: "my-key",
129
+ content: {
130
+ nodeType: "translation",
131
+ translation: {
132
+ en: "My title",
133
+ fr: "Mon titre",
134
+ },
135
+ },
136
+ });
137
+ ```
138
+
139
+ ### 2. Dynamic Mode
140
+
141
+ In dynamic mode, Intlayer replaces `useIntlayer` with `useDictionaryAsync`. This uses `import()` (Suspense-like mechanism) to lazy-load specifically the JSON for the current locale.
142
+
143
+ - **Pros:** **Locale-level tree shaking.** A user viewing the English version will _only_ download the English dictionary. The French dictionary is never loaded.
144
+ - **Cons:** Triggers a network request (asset fetch) per component during hydration.
145
+ - **Best for:** Large text blocks, articles, or applications supporting many languages where bundle size is critical.
146
+
147
+ **Transformed Code Example:**
148
+
149
+ ```tsx
150
+ // Your code
151
+ const content = useIntlayer("my-key");
152
+
153
+ // Optimised code (Dynamic)
154
+ const content = useDictionaryAsync({
155
+ en: () =>
156
+ import(".intlayer/dynamic_dictionary/en.json").then((mod) => mod.default),
157
+ fr: () =>
158
+ import(".intlayer/dynamic_dictionary/fr.json").then((mod) => mod.default),
159
+ });
160
+ ```
161
+
162
+ > When using `importMode: 'dynamic'`, if you have 100 components using `useIntlayer` on a single page, the browser will attempt 100 separate fetches. To avoid this "waterfall" of requests, group content into fewer `.content` files (e.g., one dictionary per page section) rather than one per atom component.
163
+
164
+ > Currently, `importMode: 'dynamic'` is not fully supported for Vue and Svelte. It is recommended to use `importMode: 'static'` for these frameworks until further updates.
165
+
166
+ ### 3. Live Mode
167
+
168
+ Behaves similarly to Dynamic mode but attempts to fetch dictionaries from the Intlayer Live Sync API first. If the API call fails or the content is not marked for live updates, it falls back to the dynamic import.
169
+
170
+ > See CMS documentation for more details: [CMS](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en-GB/intlayer_CMS.md)
171
+
172
+ ## Summary: Static vs Dynamic
173
+
174
+ | Feature | Static Mode | Dynamic Mode |
175
+ | :------------------- | :-------------------------------------------- | :----------------------------------- |
176
+ | **JS Bundle Size** | Larger (includes all langs for the component) | Smallest (only code, no content) |
177
+ | **Initial Load** | Instant (Content is in bundle) | Slight delay (Fetches JSON) |
178
+ | **Network Requests** | 0 extra requests | 1 request per dictionary |
179
+ | **Tree Shaking** | Component-level | Component-level + Locale-level |
180
+ | **Best Use Case** | UI Components, Small Apps | Pages with much text, Many Languages |
@@ -139,7 +139,7 @@ The `vue-intlayer` package is used to interpret Intlayer dictionaries and make t
139
139
 
140
140
  The `nuxt-intlayer` package is a Nuxt module to make Intlayer dictionaries usable in Nuxt applications. It integrates essential features to make Intlayer work in a Nuxt environment, such as translation middleware, routing, or the `nuxt.config.js` file configuration.
141
141
 
142
- ### svelte-intlayer (WIP)
142
+ ### svelte-intlayer
143
143
 
144
144
  The `svelte-intlayer` package is used to interpret Intlayer dictionaries and make them usable in Svelte applications.
145
145
 
@@ -42,6 +42,10 @@ Extension link: [https://marketplace.visualstudio.com/items?itemName=Intlayer.in
42
42
 
43
43
  ## Features
44
44
 
45
+ ![Extract content](https://github.com/aymericzip/intlayer-vs-code-extension/blob/master/assets/vscode_extention_extract_content.gif?raw=true)
46
+
47
+ - **Extract Content** – Extract content from your React / Vue / Svelte components
48
+
45
49
  ![Fill dictionaries](https://github.com/aymericzip/intlayer-vs-code-extension/blob/master/assets/vscode_extention_fill_active_dictionary.gif?raw=true)
46
50
 
47
51
  - **Instant Navigation** – Quickly jump to the correct content file when clicking on a `useIntlayer` key.
@@ -0,0 +1,190 @@
1
+ ---
2
+ createdAt: 2025-11-25
3
+ updatedAt: 2025-11-25
4
+ title: Optimización del Tamaño y Rendimiento del Bundle i18n
5
+ description: Reduce el tamaño del bundle de la aplicación optimizando el contenido de internacionalización (i18n). Aprende a aprovechar tree shaking y lazy loading para diccionarios con Intlayer.
6
+ keywords:
7
+ - Optimización de Bundle
8
+ - Automatización de Contenido
9
+ - Contenido Dinámico
10
+ - Intlayer
11
+ - Next.js
12
+ - JavaScript
13
+ - React
14
+ slugs:
15
+ - doc
16
+ - concept
17
+ - bundle-optimization
18
+ history:
19
+ - version: 6.0.0
20
+ date: 2025-11-25
21
+ changes: Historial inicial
22
+ ---
23
+
24
+ # Optimización del Tamaño y Rendimiento del Bundle i18n
25
+
26
+ Uno de los desafíos más comunes con las soluciones tradicionales de i18n que dependen de archivos JSON es gestionar el tamaño del contenido. Si los desarrolladores no separan manualmente el contenido en namespaces, los usuarios a menudo terminan descargando las traducciones de todas las páginas y potencialmente de todos los idiomas solo para ver una sola página.
27
+
28
+ Por ejemplo, una aplicación con 10 páginas traducidas a 10 idiomas podría hacer que un usuario descargue el contenido de 100 páginas, aunque solo necesite **una** (la página actual en el idioma actual). Esto conduce a un desperdicio de ancho de banda y tiempos de carga más lentos.
29
+
30
+ > Para detectarlo, puedes usar analizadores de bundle como `rollup-plugin-visualizer` (vite), `@next/bundle-analyzer` (next.js) o `webpack-bundle-analyzer` (React CRA / Angular / etc).
31
+
32
+ **Intlayer resuelve este problema mediante la optimización en tiempo de compilación.** Analiza tu código para detectar qué diccionarios se usan realmente por componente y reinserta solo el contenido necesario en tu bundle.
33
+
34
+ ## Tabla de Contenidos
35
+
36
+ <TOC />
37
+
38
+ ## Cómo Funciona
39
+
40
+ Intlayer utiliza un **enfoque por componente**. A diferencia de los archivos JSON globales, tu contenido se define junto a tus componentes o dentro de ellos. Durante el proceso de compilación, Intlayer:
41
+
42
+ 1. **Analiza** tu código para encontrar llamadas a `useIntlayer`.
43
+ 2. **Construye** el contenido del diccionario correspondiente.
44
+ 3. **Reemplaza** la llamada a `useIntlayer` con código optimizado basado en tu configuración.
45
+
46
+ Esto garantiza que:
47
+
48
+ - Si un componente no se importa, su contenido no se incluye en el bundle (Eliminación de Código Muerto).
49
+ - Si un componente se carga de forma lazy, su contenido también se carga de forma lazy.
50
+
51
+ ## Configuración por Plataforma
52
+
53
+ ### Next.js
54
+
55
+ Next.js requiere el plugin `@intlayer/swc` para manejar la transformación, ya que Next.js utiliza SWC para las compilaciones.
56
+
57
+ > Este plugin está instalado por defecto porque los plugins SWC aún son experimentales para Next.js. Esto podría cambiar en el futuro.
58
+
59
+ ### Vite
60
+
61
+ Vite utiliza el plugin `@intlayer/babel` que está incluido como dependencia de `vite-intlayer`. La optimización está habilitada por defecto.
62
+
63
+ ### Webpack
64
+
65
+ Para habilitar la optimización del bundle con Intlayer en Webpack, necesitas instalar y configurar el plugin adecuado de Babel (`@intlayer/babel`) o SWC (`@intlayer/swc`).
66
+
67
+ ### Expo / Lynx
68
+
69
+ La optimización del bundle **no está disponible aún** para esta plataforma. El soporte será añadido en una versión futura.
70
+
71
+ ## Configuración
72
+
73
+ Puedes controlar cómo Intlayer optimiza tu bundle a través de la propiedad `build` en tu archivo `intlayer.config.ts`.
74
+
75
+ ```typescript fileName="intlayer.config.ts"
76
+ import { Locales, type IntlayerConfig } from "intlayer";
77
+
78
+ const config: IntlayerConfig = {
79
+ internationalization: {
80
+ locales: [Locales.ENGLISH, Locales.FRENCH],
81
+ defaultLocale: Locales.ENGLISH,
82
+ },
83
+ build: {
84
+ optimize: true,
85
+ importMode: "static", // o 'dynamic'
86
+ traversePattern: ["**/*.{js,ts,mjs,cjs,jsx,tsx}", "!**/node_modules/**"],
87
+ },
88
+ };
89
+
90
+ export default config;
91
+ ```
92
+
93
+ > Se recomienda mantener la opción por defecto para `optimize` en la mayoría de los casos.
94
+
95
+ > Consulta la documentación de configuración para más detalles: [Configuración](https://github.com/aymericzip/intlayer/blob/main/docs/docs/es/configuration.md)
96
+
97
+ ### Opciones de Build
98
+
99
+ Las siguientes opciones están disponibles bajo el objeto de configuración `build`:
100
+
101
+ | Propiedad | Tipo | Valor por defecto | Descripción |
102
+ | :-------------------- | :------------------------------ | :------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
103
+ | **`optimize`** | `boolean` | `undefined` | Controla si la optimización de la build está habilitada. Si es `true`, Intlayer reemplaza las llamadas al diccionario con inyecciones optimizadas. Si es `false`, la optimización está deshabilitada. Idealmente se debe establecer en `true` en producción. |
104
+ | **`importMode`** | `'static' , 'dynamic' , 'live'` | `'static'` | Determina cómo se cargan los diccionarios (ver detalles a continuación). |
105
+ | **`traversePattern`** | `string[]` | `['**/*.{js,ts,jsx,tsx}', ...]` | Patrones glob que definen qué archivos Intlayer debe escanear para la optimización. Úsalo para excluir archivos no relacionados y acelerar las builds. |
106
+ | **`outputFormat`** | `'esm', 'cjs'` | `'esm', 'cjs'` | Controla el formato de salida de los diccionarios construidos. |
107
+
108
+ ## Modos de Importación
109
+
110
+ La configuración `importMode` dicta cómo se inyecta el contenido del diccionario en tu componente.
111
+
112
+ ### 1. Modo Estático (`default`)
113
+
114
+ En modo estático, Intlayer reemplaza `useIntlayer` por `useDictionary` e inyecta el diccionario directamente en el bundle de JavaScript.
115
+
116
+ - **Ventajas:** Renderizado instantáneo (síncrono), sin solicitudes de red adicionales durante la hidratación.
117
+ - **Desventajas:** El bundle incluye traducciones para **todos** los idiomas disponibles para ese componente específico.
118
+ - **Ideal para:** Aplicaciones de una sola página (SPA).
119
+
120
+ **Ejemplo de código transformado:**
121
+
122
+ ```tsx
123
+ // Tu código
124
+ const content = useIntlayer("my-key");
125
+
126
+ // Código optimizado (Estático)
127
+ const content = useDictionary({
128
+ key: "my-key",
129
+ content: {
130
+ nodeType: "translation",
131
+ translation: {
132
+ en: "My title",
133
+ fr: "Mon titre",
134
+ },
135
+ },
136
+ });
137
+ ```
138
+
139
+ ### 2. Modo Dinámico
140
+
141
+ En modo dinámico, Intlayer reemplaza `useIntlayer` por `useDictionaryAsync`. Esto utiliza `import()` (mecanismo similar a Suspense) para cargar perezosamente específicamente el JSON para la localidad actual.
142
+
143
+ - **Ventajas:** **Eliminación de código a nivel de localidad.** Un usuario que vea la versión en inglés solo descargará el diccionario en inglés. El diccionario en francés nunca se carga.
144
+ - **Desventajas:** Genera una solicitud de red (descarga de recurso) por componente durante la hidratación.
145
+ - **Ideal para:** Bloques grandes de texto, artículos o aplicaciones que soportan muchos idiomas donde el tamaño del bundle es crítico.
146
+
147
+ **Ejemplo de código transformado:**
148
+
149
+ ```tsx
150
+ // Tu código
151
+ const content = useIntlayer("my-key");
152
+
153
+ // Código optimizado (Dinámico)
154
+ const content = useDictionaryAsync({
155
+ en: () =>
156
+ import(".intlayer/dynamic_dictionary/en.json").then((mod) => mod.default),
157
+ fr: () =>
158
+ import(".intlayer/dynamic_dictionary/fr.json").then((mod) => mod.default),
159
+ });
160
+ ```
161
+
162
+ > Al usar `importMode: 'dynamic'`, si tienes 100 componentes usando `useIntlayer` en una sola página, el navegador intentará realizar 100 solicitudes separadas. Para evitar esta "cascada" de peticiones, agrupa el contenido en menos archivos `.content` (por ejemplo, un diccionario por sección de página) en lugar de uno por componente átomo.
163
+
164
+ > Actualmente, `importMode: 'dynamic'` no está completamente soportado para Vue y Svelte. Se recomienda usar `importMode: 'static'` para estos frameworks hasta futuras actualizaciones.
165
+
166
+ ### 3. Modo Live
167
+
168
+ Se comporta de manera similar al modo Dinámico, pero intenta obtener primero los diccionarios desde la API de Intlayer Live Sync. Si la llamada a la API falla o el contenido no está marcado para actualizaciones en vivo, vuelve a la importación dinámica.
169
+
170
+ > Consulta la documentación del CMS para más detalles: [CMS](https://github.com/aymericzip/intlayer/blob/main/docs/docs/es/intlayer_CMS.md)
171
+
172
+ ## Resumen: Estático vs Dinámico
173
+
174
+ | Característica | Modo Estático | Modo Dinámico |
175
+ | :----------------------- | :-------------------------------------------------------- | :--------------------------------------- |
176
+ | **Tamaño del Bundle JS** | Más grande (incluye todos los idiomas para el componente) | Más pequeño (solo código, sin contenido) |
177
+
178
+ Se comporta de manera similar al modo Dinámico pero intenta obtener los diccionarios primero desde la API de Intlayer Live Sync. Si la llamada a la API falla o el contenido no está marcado para actualizaciones en vivo, vuelve a la importación dinámica.
179
+
180
+ > Consulte la documentación del CMS para más detalles: [CMS](https://github.com/aymericzip/intlayer/blob/main/docs/docs/es/intlayer_CMS.md)
181
+
182
+ ## Resumen: Estático vs Dinámico
183
+
184
+ | Característica | Modo Estático | Modo Dinámico |
185
+ | :----------------------- | :-------------------------------------------------------- | :---------------------------------------- |
186
+ | **Tamaño del Bundle JS** | Más grande (incluye todos los idiomas para el componente) | Más pequeño (solo código, sin contenido) |
187
+ | **Carga Inicial** | Instantánea (El contenido está en el bundle) | Ligera demora (Obtiene JSON) |
188
+ | **Solicitudes de Red** | 0 solicitudes adicionales | 1 solicitud por diccionario |
189
+ | **Tree Shaking** | A nivel de componente | A nivel de componente + a nivel de idioma |
190
+ | **Mejor Caso de Uso** | Componentes UI, Aplicaciones pequeñas | Páginas con mucho texto, Muchos idiomas |
@@ -142,7 +142,7 @@ El paquete `vue-intlayer` se utiliza para interpretar los diccionarios de Intlay
142
142
 
143
143
  El paquete `nuxt-intlayer` es un módulo de Nuxt para hacer que los diccionarios de Intlayer sean utilizables en aplicaciones Nuxt. Integra características esenciales para que Intlayer funcione en un entorno Nuxt, como middleware de traducción, enrutamiento o la configuración del archivo `nuxt.config.js`.
144
144
 
145
- ### svelte-intlayer (WIP)
145
+ ### svelte-intlayer
146
146
 
147
147
  El paquete `svelte-intlayer` se utiliza para interpretar los diccionarios de Intlayer y hacerlos utilizables en aplicaciones Svelte.
148
148
 
@@ -42,6 +42,10 @@ Enlace de la extensión: [https://marketplace.visualstudio.com/items?itemName=In
42
42
 
43
43
  ## Funcionalidades
44
44
 
45
+ ![Extraer contenido](https://github.com/aymericzip/intlayer-vs-code-extension/blob/master/assets/vscode_extention_extract_content.gif?raw=true)
46
+
47
+ - **Extraer Contenido** – Extrae contenido de tus componentes React / Vue / Svelte
48
+
45
49
  ![Rellenar diccionarios](https://github.com/aymericzip/intlayer-vs-code-extension/blob/master/assets/vscode_extention_fill_active_dictionary.gif?raw=true)
46
50
 
47
51
  - **Navegación Instantánea** – Salta rápidamente al archivo de contenido correcto al hacer clic en una clave `useIntlayer`.
@@ -0,0 +1,180 @@
1
+ ---
2
+ createdAt: 2025-11-25
3
+ updatedAt: 2025-11-25
4
+ title: Optimisation de la taille et des performances du bundle i18n
5
+ description: Réduisez la taille du bundle de votre application en optimisant le contenu d'internationalisation (i18n). Apprenez à exploiter le tree shaking et le lazy loading pour les dictionnaires avec Intlayer.
6
+ keywords:
7
+ - Optimisation du bundle
8
+ - Automatisation du contenu
9
+ - Contenu dynamique
10
+ - Intlayer
11
+ - Next.js
12
+ - JavaScript
13
+ - React
14
+ slugs:
15
+ - doc
16
+ - concept
17
+ - bundle-optimization
18
+ history:
19
+ - version: 6.0.0
20
+ date: 2025-11-25
21
+ changes: Historique initial
22
+ ---
23
+
24
+ # Optimisation de la taille et des performances du bundle i18n
25
+
26
+ L'un des défis les plus courants avec les solutions i18n traditionnelles basées sur des fichiers JSON est la gestion de la taille du contenu. Si les développeurs ne séparent pas manuellement le contenu en namespaces, les utilisateurs finissent souvent par télécharger les traductions de chaque page et potentiellement de chaque langue simplement pour afficher une seule page.
27
+
28
+ Par exemple, une application avec 10 pages traduites en 10 langues peut entraîner le téléchargement par un utilisateur du contenu de 100 pages, alors qu'il n'a besoin que d'**une seule** (la page actuelle dans la langue actuelle). Cela conduit à un gaspillage de bande passante et à des temps de chargement plus lents.
29
+
30
+ > Pour le détecter, vous pouvez utiliser un analyseur de bundle comme `rollup-plugin-visualizer` (vite), `@next/bundle-analyzer` (next.js), ou `webpack-bundle-analyzer` (React CRA / Angular / etc).
31
+
32
+ **Intlayer résout ce problème grâce à une optimisation au moment de la compilation.** Il analyse votre code pour détecter quels dictionnaires sont réellement utilisés par composant et réinjecte uniquement le contenu nécessaire dans votre bundle.
33
+
34
+ ## Table des matières
35
+
36
+ <TOC />
37
+
38
+ ## Comment ça fonctionne
39
+
40
+ Intlayer utilise une **approche par composant**. Contrairement aux fichiers JSON globaux, votre contenu est défini à côté ou à l'intérieur de vos composants. Lors du processus de build, Intlayer :
41
+
42
+ 1. **Analyse** votre code pour trouver les appels à `useIntlayer`.
43
+ 2. **Construit** le contenu du dictionnaire correspondant.
44
+ 3. **Remplace** l'appel à `useIntlayer` par un code optimisé basé sur votre configuration.
45
+
46
+ Cela garantit que :
47
+
48
+ - Si un composant n'est pas importé, son contenu n'est pas inclus dans le bundle (élimination de code mort).
49
+ - Si un composant est chargé de manière lazy, son contenu est également chargé de manière lazy.
50
+
51
+ ## Configuration par plateforme
52
+
53
+ ### Next.js
54
+
55
+ Next.js nécessite le plugin `@intlayer/swc` pour gérer la transformation, car Next.js utilise SWC pour les builds.
56
+
57
+ > Ce plugin est installé par défaut car les plugins SWC sont encore expérimentaux pour Next.js. Cela pourrait changer à l'avenir.
58
+
59
+ ### Vite
60
+
61
+ Vite utilise le plugin `@intlayer/babel` qui est inclus en tant que dépendance de `vite-intlayer`. L'optimisation est activée par défaut.
62
+
63
+ ### Webpack
64
+
65
+ Pour activer l'optimisation du bundle avec Intlayer sur Webpack, vous devez installer et configurer le plugin Babel (`@intlayer/babel`) ou SWC (`@intlayer/swc`) approprié.
66
+
67
+ ### Expo / Lynx
68
+
69
+ L'optimisation du bundle n'est **pas encore disponible** pour cette plateforme. Le support sera ajouté dans une future version.
70
+
71
+ ## Configuration
72
+
73
+ Vous pouvez contrôler la manière dont Intlayer optimise votre bundle via la propriété `build` dans votre fichier `intlayer.config.ts`.
74
+
75
+ ```typescript fileName="intlayer.config.ts"
76
+ import { Locales, type IntlayerConfig } from "intlayer";
77
+
78
+ const config: IntlayerConfig = {
79
+ internationalization: {
80
+ locales: [Locales.ENGLISH, Locales.FRENCH],
81
+ defaultLocale: Locales.ENGLISH,
82
+ },
83
+ build: {
84
+ optimize: true,
85
+ importMode: "static", // ou 'dynamic'
86
+ traversePattern: ["**/*.{js,ts,mjs,cjs,jsx,tsx}", "!**/node_modules/**"],
87
+ },
88
+ };
89
+
90
+ export default config;
91
+ ```
92
+
93
+ > Il est recommandé de conserver l'option par défaut pour `optimize` dans la grande majorité des cas.
94
+
95
+ > Voir la documentation de configuration pour plus de détails : [Configuration](https://github.com/aymericzip/intlayer/blob/main/docs/docs/fr/configuration.md)
96
+
97
+ ### Options de build
98
+
99
+ Les options suivantes sont disponibles sous l'objet de configuration `build` :
100
+
101
+ | Propriété | Type | Par défaut | Description |
102
+ | :-------------------- | :------------------------------ | :------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
103
+ | **`optimize`** | `boolean` | `undefined` | Contrôle si l'optimisation de la build est activée. Si `true`, Intlayer remplace les appels au dictionnaire par des injections optimisées. Si `false`, l'optimisation est désactivée. Idéalement configuré à `true` en production. |
104
+ | **`importMode`** | `'static' , 'dynamic' , 'live'` | `'static'` | Détermine comment les dictionnaires sont chargés (voir détails ci-dessous). |
105
+ | **`traversePattern`** | `string[]` | `['**/*.{js,ts,jsx,tsx}', ...]` | Modèles globaux définissant les fichiers que Intlayer doit analyser pour l'optimisation. Utilisez ceci pour exclure les fichiers non pertinents et accélérer les builds. |
106
+ | **`outputFormat`** | `'esm', 'cjs'` | `'esm', 'cjs'` | Contrôle le format de sortie des dictionnaires construits. |
107
+
108
+ ## Modes d'importation
109
+
110
+ Le paramètre `importMode` détermine comment le contenu du dictionnaire est injecté dans votre composant.
111
+
112
+ ### 1. Mode statique (`default`)
113
+
114
+ En mode statique, Intlayer remplace `useIntlayer` par `useDictionary` et injecte le dictionnaire directement dans le bundle JavaScript.
115
+
116
+ - **Avantages :** Rendu instantané (synchrone), aucune requête réseau supplémentaire lors de l'hydratation.
117
+ - **Inconvénients :** Le bundle inclut les traductions pour **toutes** les langues disponibles pour ce composant spécifique.
118
+ - **Idéal pour :** Applications monopage (SPA).
119
+
120
+ **Exemple de code transformé :**
121
+
122
+ ```tsx
123
+ // Votre code
124
+ const content = useIntlayer("my-key");
125
+
126
+ // Code optimisé (Statique)
127
+ const content = useDictionary({
128
+ key: "my-key",
129
+ content: {
130
+ nodeType: "translation",
131
+ translation: {
132
+ en: "My title",
133
+ fr: "Mon titre",
134
+ },
135
+ },
136
+ });
137
+ ```
138
+
139
+ ### 2. Mode Dynamique
140
+
141
+ En mode dynamique, Intlayer remplace `useIntlayer` par `useDictionaryAsync`. Cela utilise `import()` (mécanisme similaire à Suspense) pour charger paresseusement le JSON spécifique à la locale courante.
142
+
143
+ - **Avantages :** **Élimination des modules inutilisés au niveau de la locale.** Un utilisateur visualisant la version anglaise téléchargera _uniquement_ le dictionnaire anglais. Le dictionnaire français n'est jamais chargé.
144
+ - **Inconvénients :** Déclenche une requête réseau (récupération d'asset) par composant lors de l'hydratation.
145
+ - **Idéal pour :** Blocs de texte volumineux, articles, ou applications supportant de nombreuses langues où la taille du bundle est critique.
146
+
147
+ **Exemple de code transformé :**
148
+
149
+ ```tsx
150
+ // Votre code
151
+ const content = useIntlayer("my-key");
152
+
153
+ // Code optimisé (Dynamique)
154
+ const content = useDictionaryAsync({
155
+ en: () =>
156
+ import(".intlayer/dynamic_dictionary/en.json").then((mod) => mod.default),
157
+ fr: () =>
158
+ import(".intlayer/dynamic_dictionary/fr.json").then((mod) => mod.default),
159
+ });
160
+ ```
161
+
162
+ > Lors de l'utilisation de `importMode: 'dynamic'`, si vous avez 100 composants utilisant `useIntlayer` sur une seule page, le navigateur tentera 100 requêtes distinctes. Pour éviter cette "cascade" de requêtes, regroupez le contenu dans moins de fichiers `.content` (par exemple, un dictionnaire par section de page) plutôt qu'un par composant atomique.
163
+
164
+ > Actuellement, `importMode: 'dynamic'` n'est pas entièrement pris en charge pour Vue et Svelte. Il est recommandé d'utiliser `importMode: 'static'` pour ces frameworks en attendant des mises à jour ultérieures.
165
+
166
+ ### 3. Mode Live
167
+
168
+ Se comporte de manière similaire au mode Dynamique mais tente d'abord de récupérer les dictionnaires via l'API Intlayer Live Sync. Si l'appel API échoue ou si le contenu n'est pas marqué pour des mises à jour en direct, il revient à l'import dynamique.
169
+
170
+ > Voir la documentation CMS pour plus de détails : [CMS](https://github.com/aymericzip/intlayer/blob/main/docs/docs/fr/intlayer_CMS.md)
171
+
172
+ ## Résumé : Statique vs Dynamique
173
+
174
+ | Fonctionnalité | Mode Statique | Mode Dynamique |
175
+ | :---------------------- | :-------------------------------------------------------- | :---------------------------------------------- |
176
+ | **Taille du bundle JS** | Plus grande (inclut toutes les langues pour le composant) | Plus petite (seulement le code, pas le contenu) |
177
+ | **Chargement initial** | Instantané (Le contenu est dans le bundle) | Légère attente (Récupère du JSON) |
178
+ | **Requêtes réseau** | 0 requêtes supplémentaires | 1 requête par dictionnaire |
179
+ | **Tree Shaking** | Niveau composant | Niveau composant + niveau langue |
180
+ | **Cas d'utilisation** | Composants UI, petites applications | Pages avec beaucoup de texte, plusieurs langues |