Skip to content

Commit a5f32c2

Browse files
LuisRevillaMcarburo
authored andcommitted
Translate Code-Splitting (#145)
1 parent 38fc4c7 commit a5f32c2

File tree

1 file changed

+53
-71
lines changed

1 file changed

+53
-71
lines changed

content/docs/code-splitting.md

+53-71
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,14 @@ title: Code-Splitting
44
permalink: docs/code-splitting.html
55
---
66

7-
## Bundling {#bundling}
7+
## *Bundling* {#bundling}
88

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.
1413

15-
#### Example {#example}
14+
#### Ejemplo {#example}
1615

1716
**App:**
1817

@@ -40,86 +39,72 @@ function add(a, b) {
4039
console.log(add(16, 26)); // 42
4140
```
4241

43-
> Note:
42+
> Nota:
4443
>
45-
> Your bundles will end up looking a lot different than this.
44+
> Tus *bundles* van a lucir muy diferente a esto.
4645
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.
4947

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.
5450

55-
## Code Splitting {#code-splitting}
51+
## División de código {#code-splitting}
5652

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.
6155

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.
6862

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.
7463

7564
## `import()` {#import}
7665

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.
7967

80-
**Before:**
68+
**Antes:**
8169

8270
```js
8371
import { add } from './math';
8472

8573
console.log(add(16, 26));
8674
```
8775

88-
**After:**
76+
**Después:**
8977

9078
```js
9179
import("./math").then(math => {
9280
console.log(math.add(16, 26));
9381
});
9482
```
9583

96-
> Note:
84+
> Nota:
9785
>
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
10290
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).
10794

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).
11096

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).
11398

11499
## `React.lazy` {#reactlazy}
115100

116-
> Note:
101+
> Nota:
117102
>
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).
119104
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.
121106

122-
**Before:**
107+
**Antes:**
123108

124109
```js
125110
import OtherComponent from './OtherComponent';
@@ -133,7 +118,7 @@ function MyComponent() {
133118
}
134119
```
135120

136-
**After:**
121+
**Después:**
137122

138123
```js
139124
const OtherComponent = React.lazy(() => import('./OtherComponent'));
@@ -147,13 +132,14 @@ function MyComponent() {
147132
}
148133
```
149134

150-
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.
151138

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.
153139

154140
### Suspense {#suspense}
155141

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`.
157143

158144
```js
159145
const OtherComponent = React.lazy(() => import('./OtherComponent'));
@@ -169,7 +155,7 @@ function MyComponent() {
169155
}
170156
```
171157

172-
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`.
173159

174160
```js
175161
const OtherComponent = React.lazy(() => import('./OtherComponent'));
@@ -189,9 +175,9 @@ function MyComponent() {
189175
}
190176
```
191177

192-
### Error boundaries {#error-boundaries}
178+
### Límites de error {#error-boundaries}
193179

194-
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.
195181

196182
```js
197183
import MyErrorBoundary from './MyErrorBoundary';
@@ -212,19 +198,14 @@ const MyComponent = () => (
212198
);
213199
```
214200

215-
## Route-based code splitting {#route-based-code-splitting}
201+
## División de código basada en rutas {#route-based-code-splitting}
216202

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.
220204

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.
225206

226-
Here's an example of how to setup route-based code splitting into your app using
227-
libraries like [React Router](https://reacttraining.com/react-router/) with `React.lazy`.
207+
Este es un ejemplo de cómo configurar la división de código basada en rutas en tu aplicación usando
208+
bibliotecas como [React Router](https://reacttraining.com/react-router/) con `React.lazy`.
228209

229210
```js
230211
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
@@ -245,9 +226,10 @@ const App = () => (
245226
);
246227
```
247228

248-
## Named Exports {#named-exports}
229+
## Exports con nombres {#named-exports}
230+
231+
`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.
249232

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.
251233

252234
```js
253235
// ManyComponents.js

0 commit comments

Comments
 (0)