You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/docs/code-splitting.md
+53-71
Original file line number
Diff line number
Diff line change
@@ -4,15 +4,14 @@ title: Code-Splitting
4
4
permalink: docs/code-splitting.html
5
5
---
6
6
7
-
## Bundling {#bundling}
7
+
## *Bundling* {#bundling}
8
8
9
-
Most React apps will have their files "bundled" using tools like
10
-
[Webpack](https://webpack.js.org/) or [Browserify](http://browserify.org/).
11
-
Bundling is the process of following imported files and merging them into a
12
-
single file: a "bundle". This bundle can then be included on a webpage to load
13
-
an entire app at once.
9
+
La mayoría de las aplicaciones React tendrán sus archivos "empaquetados" o *bundled* con herramientas como
10
+
[Webpack](https://webpack.js.org/) o [Browserify](http://browserify.org/).
11
+
El *bundling* es el proceso de seguir los archivos importados y fusionarlos en un
12
+
archivo único: un *bundle* o "paquete". Este *bundle* se puede incluir en una página web para cargar una aplicación completa de una sola vez.
14
13
15
-
#### Example {#example}
14
+
#### Ejemplo {#example}
16
15
17
16
**App:**
18
17
@@ -40,86 +39,72 @@ function add(a, b) {
40
39
console.log(add(16, 26)); // 42
41
40
```
42
41
43
-
> Note:
42
+
> Nota:
44
43
>
45
-
> Your bundles will end up looking a lot different than this.
44
+
> Tus *bundles* van a lucir muy diferente a esto.
46
45
47
-
If you're using [Create React App](https://github.com/facebookincubator/create-react-app), [Next.js](https://github.com/zeit/next.js/), [Gatsby](https://www.gatsbyjs.org/), or a similar tool, you will have a Webpack setup out of the box to bundle your
48
-
app.
46
+
Si usas [Create React App](https://github.com/facebookincubator/create-react-app), [Next.js](https://github.com/zeit/next.js/), [Gatsby](https://www.gatsbyjs.org/), o una herramienta similar, vas a tener una configuración de Webpack incluida para generar el *bundle* de tu aplicación.
49
47
50
-
If you aren't, you'll need to setup bundling yourself. For example, see the
51
-
[Installation](https://webpack.js.org/guides/installation/) and
52
-
[Getting Started](https://webpack.js.org/guides/getting-started/) guides on the
53
-
Webpack docs.
48
+
Si no, tú mismo vas a tener que configurar el *bundling*. Por ejemplo, revisa las guías [Installation](https://webpack.js.org/guides/installation/) y
49
+
[Getting Started](https://webpack.js.org/guides/getting-started/) en la documentación de Webpack.
54
50
55
-
## Code Splitting {#code-splitting}
51
+
## División de código {#code-splitting}
56
52
57
-
Bundling is great, but as your app grows, your bundle will grow too. Especially
58
-
if you are including large third-party libraries. You need to keep an eye on
59
-
the code you are including in your bundle so that you don't accidentally make
60
-
it so large that your app takes a long time to load.
53
+
El *Bundling* es genial, pero a medida que tu aplicación crezca, tu *bundle* también crecerá. Especialmente
54
+
si incluyes grandes bibliotecas de terceros. Necesitas vigilar el código que incluyes en tu *bundle*, de manera que no lo hagas accidentalmente tan grande que tu aplicación se tome mucho tiempo en cargar.
61
55
62
-
To avoid winding up with a large bundle, it's good to get ahead of the problem
63
-
and start "splitting" your bundle.
64
-
[Code-Splitting](https://webpack.js.org/guides/code-splitting/) is a feature
65
-
supported by bundlers like Webpack and Browserify (via
66
-
[factor-bundle](https://github.com/browserify/factor-bundle)) which can create
67
-
multiple bundles that can be dynamically loaded at runtime.
56
+
Para evitar terminar con un *bundle* grande, es bueno adelantarse al problema
57
+
y comenzar a dividir tu *bundle*. [División de código](https://webpack.js.org/guides/code-splitting/) es una funcionalidad disponible en *bundlers* como Webpack y Browserify (vía [factor-bundle](https://github.com/browserify/factor-bundle)) que puede crear múltiples *bundles* a ser cargados dinámicamente durante la ejecución de tu aplicación.
58
+
59
+
Dividir el código de tu aplicación puede ayudarte a cargar solo lo necesario en cada momento para el usuario, lo cual puede mejorar dramáticamente el rendimiento de tu aplicación. Si bien no habrás reducido la cantidad total de código en tu aplicación,
60
+
habrás evitado cargar código que el usuario podría no necesitar nunca, y reducido la cantidad necesaria
61
+
de código durante la carga inicial.
68
62
69
-
Code-splitting your app can help you "lazy-load" just the things that are
70
-
currently needed by the user, which can dramatically improve the performance of
71
-
your app. While you haven't reduced the overall amount of code in your app,
72
-
you've avoided loading code that the user may never need, and reduced the amount
73
-
of code needed during the initial load.
74
63
75
64
## `import()` {#import}
76
65
77
-
The best way to introduce code-splitting into your app is through the dynamic
78
-
`import()` syntax.
66
+
La mejor manera de introducir división de código en tu aplicación es a través de la sintaxis de `import()` dinámico.
79
67
80
-
**Before:**
68
+
**Antes:**
81
69
82
70
```js
83
71
import { add } from'./math';
84
72
85
73
console.log(add(16, 26));
86
74
```
87
75
88
-
**After:**
76
+
**Después:**
89
77
90
78
```js
91
79
import("./math").then(math=> {
92
80
console.log(math.add(16, 26));
93
81
});
94
82
```
95
83
96
-
> Note:
84
+
> Nota:
97
85
>
98
-
> The dynamic `import()`syntax is a ECMAScript (JavaScript)
99
-
> [proposal](https://github.com/tc39/proposal-dynamic-import) not currently
100
-
> part of the language standard. It is expected to be accepted in the
101
-
> near future.
86
+
> La sintaxis de `import()`dinámico es una [propuesta](https://github.com/tc39/proposal-dynamic-import)
87
+
> ECMAScript (JavaScript) que no es parte actual del estándar
88
+
> del lenguaje. Se espera que sea aceptada en el
89
+
> futuro cercano
102
90
103
-
When Webpack comes across this syntax, it automatically starts code-splitting
104
-
your app. If you're using Create React App, this is already configured for you
105
-
and you can [start using it](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#code-splitting) immediately. It's also supported
106
-
out of the box in [Next.js](https://github.com/zeit/next.js/#dynamic-import).
91
+
Cuando Webpack se encuentra esta sintaxis, comienza a dividir el código de tu
92
+
aplicación automáticamente. Si estás usando Create React App, esto ya viene
93
+
configurado para ti y puedes comenzar a [usarlo](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#code-splitting). También es compatible por defecto en [Next.js](https://github.com/zeit/next.js/#dynamic-import).
107
94
108
-
If you're setting up Webpack yourself, you'll probably want to read Webpack's
109
-
[guide on code splitting](https://webpack.js.org/guides/code-splitting/). Your Webpack config should look vaguely [like this](https://gist.github.com/gaearon/ca6e803f5c604d37468b0091d9959269).
95
+
Si configuras Webpack por ti mismo, probablemente vas a querer leer la [guía sobre división de código](https://webpack.js.org/guides/code-splitting/) de Webpack. Tu configuración de Webpack debería verse vagamente [como esta](https://gist.github.com/gaearon/ca6e803f5c604d37468b0091d9959269).
110
96
111
-
When using [Babel](http://babeljs.io/), you'll need to make sure that Babel can
112
-
parse the dynamic import syntax but is not transforming it. For that you will need [babel-plugin-syntax-dynamic-import](https://yarnpkg.com/en/package/babel-plugin-syntax-dynamic-import).
97
+
Cuando uses [Babel](http://babeljs.io/), tienes que asegurarte de que Babel reconozca la sintaxis de `import()` dinámico pero no la transforme. Para ello vas a necesitar el [babel-plugin-syntax-dynamic-import](https://yarnpkg.com/en/package/babel-plugin-syntax-dynamic-import).
113
98
114
99
## `React.lazy` {#reactlazy}
115
100
116
-
> Note:
101
+
> Nota:
117
102
>
118
-
> `React.lazy`and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we recommend [Loadable Components](https://github.com/smooth-code/loadable-components). It has a nice [guide for bundle splitting with server-side rendering](https://github.com/smooth-code/loadable-components/blob/master/packages/server/README.md).
103
+
> `React.lazy`y Suspense aún no están disponibles para hacer renderización del lado del servidor. Si quieres hacer división de código en una aplicación renderizada en el servidor, recomendamos [Loadable Components](https://github.com/smooth-code/loadable-components). Tiene una buena [guía para dividir bundles con renderización del lado del servidor](https://github.com/smooth-code/loadable-components/blob/master/packages/server/README.md).
119
104
120
-
The `React.lazy`function lets you render a dynamic import as a regular component.
105
+
La función `React.lazy`te deja renderizar un *import* dinámico como un componente regular.
This will automatically load the bundle containing the `OtherComponent` when this component gets rendered.
135
+
Esto va a cargar automáticamente el *bundle* que contiene a `OtherComponent` cuando este componente sea renderizado.
136
+
137
+
`React.lazy` recibe una función que debe ejecutar un `import()` dinámico. Este debe retornar una `Promise` que se resuelve en un módulo con un *export*`default` que contenga un componente de React.
151
138
152
-
`React.lazy` takes a function that must call a dynamic `import()`. This must return a `Promise` which resolves to a module with a `default` export containing a React component.
153
139
154
140
### Suspense {#suspense}
155
141
156
-
If the module containing the `OtherComponent`is not yet loaded by the time `MyComponent`renders, we must show some fallback content while we're waiting for it to load - such as a loading indicator. This is done using the `Suspense` component.
142
+
Si el módulo que contiene a `OtherComponent`aún no ha sido cargado cuando `MyComponent`es renderizado, debemos mostrar algún contenido por defecto mientras esperamos que cargue - como un indicador de carga. Esto se hace usando el componente `Suspense`.
The `fallback`prop accepts any React elements that you want to render while waiting for the component to load. You can place the`Suspense`component anywhere above the lazy component. You can even wrap multiple lazy components with a single`Suspense` component.
158
+
El prop `fallback`acepta cualquier elemento de React que quieras renderizar mientas esperas que `OtherComponent` cargue. Puedes poner el componente`Suspense`en cualquier parte sobre el componente lazy. Incluso puedes envolver múltiples componentes lazy con un solo componente`Suspense`.
If the other module fails to load (for example, due to network failure), it will trigger an error. You can handle these errors to show a nice user experience and manage recovery with [Error Boundaries](/docs/error-boundaries.html). Once you've created your Error Boundary, you can use it anywhere above your lazy components to display an error state when there's a network error.
180
+
Si el otro módulo no se carga (por ejemplo, debido a un fallo de la red), se generará un error. Puedes manejar estos errores para mostrar una buena experiencia de usuario y manejar la recuperación con [Límites de error](/docs/error-boundaries.html). Una vez hayas creado tu límite de error (Error Boundary) puedes usarlo en cualquier parte sobre tus componentes lazy para mostrar un estado de error cuando haya un error de red.
## División de código basada en rutas {#route-based-code-splitting}
216
202
217
-
Deciding where in your app to introduce code splitting can be a bit tricky. You
218
-
want to make sure you choose places that will split bundles evenly, but won't
219
-
disrupt the user experience.
203
+
Decidir en qué parte de tu aplicación introducir la división de código puede ser un poco complicado. Quieres asegurarte de elegir lugares que dividan los *bundles* de manera uniforme, sin interrumpir la experiencia del usuario.
220
204
221
-
A good place to start is with routes. Most people on the web are used to
222
-
page transitions taking some amount of time to load. You also tend to be
223
-
re-rendering the entire page at once so your users are unlikely to be
224
-
interacting with other elements on the page at the same time.
205
+
Un buen lugar para comenzar es con las rutas. La mayoría de la gente en la web está acostumbrada a que las transiciones entre páginas se tomen cierto tiempo en cargar. También tiendes a rerenderizar toda de una vez, así que es improbable que tus usuarios interactúen con otros elementos en la página al mismo tiempo.
225
206
226
-
Here's an example of how to setup route-based code splitting into your app using
`React.lazy` actualmente solo admite *exports* tipo `default`. Si el módulo que desea importar utiliza *exports* con nombre, puede crear un módulo intermedio que lo vuelva a exportar como `default`. Esto garantiza que el *treeshaking* siga funcionando y que no importes componentes no utilizados.
249
232
250
-
`React.lazy` currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that treeshaking keeps working and that you don't pull in unused components.
0 commit comments