Skip to content
This repository has been archived by the owner on Apr 21, 2023. It is now read-only.

Translate docs/code-splitting.md #52

Merged
merged 5 commits into from Jun 30, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
117 changes: 41 additions & 76 deletions content/docs/code-splitting.md
@@ -1,21 +1,17 @@
---
id: code-splitting
title: Code-Splitting
title: Divisão de Código
permalink: docs/code-splitting.html
---

## Bundling {#bundling}
## Empacotamento {#bundling}

Most React apps will have their files "bundled" using tools like
[Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/) or
[Browserify](http://browserify.org/).
Bundling is the process of following imported files and merging them into a
single file: a "bundle". This bundle can then be included on a webpage to load
an entire app at once.
A maioria das aplicações em React têm os seus ficheiros empacotados através de ferramentas como [Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/) ou [Browserify](http://browserify.org/).
Empacotamento é o processo que converte vários ficheiros importados num único ficheiro: um pacote. Este ficheiro empacotado pode ser depois incluído numa página web para carregar uma aplicação inteira de uma só vez.

#### Example {#example}
#### Exemplo {#example}

**App:**
**Aplicação:**

```js
// app.js
Expand All @@ -31,7 +27,7 @@ export function add(a, b) {
}
```

**Bundle:**
**Pacote:**

```js
function add(a, b) {
Expand All @@ -41,102 +37,77 @@ function add(a, b) {
console.log(add(16, 26)); // 42
```

> Note:
> Nota:
>
> Your bundles will end up looking a lot different than this.
> Os teus pacotes vão ser bastante diferentes do exemplo anterior.

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
app.
Se estás a usar [Create React App](https://github.com/facebookincubator/create-react-app), [Next.js](https://github.com/zeit/next.js/), [Gatsby](https://www.gatsbyjs.org/), ou uma ferramenta semelhante, terás uma configuração predefinida do Webpack para empacotar a tua aplicação.

If you aren't, you'll need to setup bundling yourself. For example, see the
[Installation](https://webpack.js.org/guides/installation/) and
[Getting Started](https://webpack.js.org/guides/getting-started/) guides on the
Webpack docs.
Senão, terás de configurar o empacotamento tu mesmo. Para referência, podes ver os guias de [Instalação](https://webpack.js.org/guides/installation/) e [Introdução](https://webpack.js.org/guides/getting-started/) na documentação do Webpack.

## Code Splitting {#code-splitting}
## Divisão de Código {#code-splitting}

Bundling is great, but as your app grows, your bundle will grow too. Especially
if you are including large third-party libraries. You need to keep an eye on
the code you are including in your bundle so that you don't accidentally make
it so large that your app takes a long time to load.
Empacotamento é ótimo, mas, à medida que a tua aplicação cresce, o pacote cresce também. Especialmente se estiveres a incluir bibliotecas de terceiros de grandes dimensões. Tens de ficar atento ao código que estás a incluir no teu pacote, para que não o faças tão grande ao ponto que torne a aplicação muito lenta a carregar.

To avoid winding up with a large bundle, it's good to get ahead of the problem
and start "splitting" your bundle.
[Code-Splitting](https://webpack.js.org/guides/code-splitting/) is a feature
supported by bundlers like Webpack and Browserify (via
[factor-bundle](https://github.com/browserify/factor-bundle)) which can create
multiple bundles that can be dynamically loaded at runtime.
Para evitar acabar com um pacote grande, é bom antecipar o problema e começar a “dividir” o pacote. A divisão de código é um recurso suportado por empacotadores como o Webpack, Rollup e Browserify (através do coeficiente de empacotamento ([factor-bundle](https://github.com/browserify/factor-bundle))) que podem criar múltiplos pacotes, que são posteriormente carregados dinamicamente em tempo de execução.
reinaldosimoes marked this conversation as resolved.
Show resolved Hide resolved

Code-splitting your app can help you "lazy-load" just the things that are
currently needed by the user, which can dramatically improve the performance of
your app. While you haven't reduced the overall amount of code in your app,
you've avoided loading code that the user may never need, and reduced the amount
of code needed during the initial load.
Dividir o código da aplicação pode-te ajudar a carregar somente o necessário ao utilizador, o que pode melhorar dramaticamente o desempenho da aplicação. Apesar de não ter reduzido a quantidade total de código da aplicação, acabou por evitar carregar código que o utilizador talvez nunca precise e reduziu o código inicial necessário para carregar a aplicação.
reinaldosimoes marked this conversation as resolved.
Show resolved Hide resolved

## `import()` {#import}

The best way to introduce code-splitting into your app is through the dynamic
`import()` syntax.
A melhor forma de introduzir divisão de código na aplicação é através da sintaxe dinâmica `import()`.

**Before:**
**Antes:**

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

console.log(add(16, 26));
```

**After:**
**Depois:**

```js
import("./math").then(math => {
console.log(math.add(16, 26));
});
```

> Note:
>
> The dynamic `import()` syntax is a ECMAScript (JavaScript)
> [proposal](https://github.com/tc39/proposal-dynamic-import) not currently
> part of the language standard. It is expected to be accepted in the
> near future.
> Nota:
>
>A sintaxe dinâmica `import()` é uma [proposta](https://github.com/tc39/proposal-dynamic-import) da ECMAScript (JavaScript) que ainda não faz parte da linguagem. Espera-se que seja aceite em breve.

When Webpack comes across this syntax, it automatically starts code-splitting
your app. If you're using Create React App, this is already configured for you
and you can [start using it](https://facebook.github.io/create-react-app/docs/code-splitting) immediately. It's also supported
out of the box in [Next.js](https://github.com/zeit/next.js/#dynamic-import).
Quando o Webpack encontra esta sintaxe, a divisão do código da aplicação é automaticamente feita. Se estás a usar Create React App, isto já está configurado e podes [começar a usar](https://facebook.github.io/create-react-app/docs/code-splitting) imediatamente. Também é suportado por predefinição no [Next.js](https://github.com/zeit/next.js/#dynamic-import).
reinaldosimoes marked this conversation as resolved.
Show resolved Hide resolved

If you're setting up Webpack yourself, you'll probably want to read Webpack's
[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).
Se estiveres a configurar o Webpack manualmente, provavelmente vais querer ler o [guia em como dividir código](https://webpack.js.org/guides/code-splitting/) do Webpack. A tua configuração deverá ser algo parecida a [isto](https://gist.github.com/gaearon/ca6e803f5c604d37468b0091d9959269).

When using [Babel](https://babeljs.io/), you'll need to make sure that Babel can
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).
Ao usar [Babel](https://babeljs.io/), terás de ter a certeza que o Babel consegue analisar a sintaxe de importação dinâmica e que não a esteja a transformar. Para tal, vais precisar do [babel-plugin-syntax-dynamic-import](https://yarnpkg.com/en/package/babel-plugin-syntax-dynamic-import).

## `React.lazy` {#reactlazy}

> Note:
> Nota:
>
> `React.lazy` and Suspense are 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).
> `React.lazy` e Suspense não estão ainda disponíveis para renderização no lado do servidor. Se quiseres fazer divisão de código neste sentido, recomendamos usar o pacote [Loadable Components](https://github.com/smooth-code/loadable-components). Este tem um ótimo [guia de como fazer divisão de código no lado do servidor](https://github.com/smooth-code/loadable-components/blob/master/packages/server/README.md).

The `React.lazy` function lets you render a dynamic import as a regular component.
A função `React.lazy` permite-te renderizar uma importação dinâmica como se fosse um componente comum.

**Before:**
**Antes:**

```js
import OtherComponent from './OtherComponent';
```

**After:**
**Depois:**

```js
const OtherComponent = React.lazy(() => import('./OtherComponent'));
```

This will automatically load the bundle containing the `OtherComponent` when this component is first rendered.
Isto vai automaticamente carregar o pacote que contém o `OtherComponent` quando este componente é renderizado pela primeira vez.

`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.
O `React.lazy` recebe uma função que deve chamar um `import()` dinâmico. Este último retorna uma Promise que é resolvida para um módulo com um export default que contém um componente React.

The lazy component should then be rendered inside a `Suspense` component, which allows us to show some fallback content (such as a loading indicator) while we're waiting for the lazy component to load.
O componente dinâmico (ou lazy) pode ser renderizado dentro de um componente `Suspense`, o que nos permite mostrar algum conteúdo como fallback (um indicador de carregamento, por exemplo) enquanto esperamos pelo carregamento do componente dinâmico.

```js
const OtherComponent = React.lazy(() => import('./OtherComponent'));
Expand All @@ -152,7 +123,7 @@ function MyComponent() {
}
```

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.
A propriedade `fallback` aceita qualquer elemento React que queiras que seja renderizado enquanto esperas que o componente seja carregado completamente. Podes colocar o componente `Suspense` em qualquer lugar acima do componente dinâmico. Podes até ter vários componentes dinâmicos dentro de apenas um componente `Suspense`.

```js
const OtherComponent = React.lazy(() => import('./OtherComponent'));
Expand All @@ -172,9 +143,9 @@ function MyComponent() {
}
```

### Error boundaries {#error-boundaries}
### Limites de Erro {#error-boundaries}

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.
Se um outro módulo não for carregado (por exemplo, devido a uma falha na conexão), será disparado um erro. Estes erros podem ser manipulados para dar ao utilizador uma boa experiência de utilização e gerir a recuperação atráves de [Limites de Erro](/docs/error-boundaries.html). Quando um Limite de Erro é criado, podes usá-lo em qualquer lugar acima dos teus componentes dinâmicos para exibir uma mensagem de erro quando houver uma falha de conexão.
fjoshuajr marked this conversation as resolved.
Show resolved Hide resolved

```js
import MyErrorBoundary from './MyErrorBoundary';
Expand All @@ -195,19 +166,13 @@ const MyComponent = () => (
);
```

## Route-based code splitting {#route-based-code-splitting}
## Divisão de código baseado em rotas {#route-based-code-splitting}

Deciding where in your app to introduce code splitting can be a bit tricky. You
want to make sure you choose places that will split bundles evenly, but won't
disrupt the user experience.
Decidir onde introduzir a divisão de código na aplicação pode ser complicado. Tens de ter a certeza que escolhes os lugares que irão dividir os pacotes de igual modo, mas que não afetem a experiência do utilizador.

A good place to start is with routes. Most people on the web are used to
page transitions taking some amount of time to load. You also tend to be
re-rendering the entire page at once so your users are unlikely to be
interacting with other elements on the page at the same time.
Um bom lugar para começar é nas rotas. A maioria das pessoas na web estão familiarizadas com transições entre páginas que levam algum tempo para carregar. Muito provavelmente estás a re-renderizar toda a página de uma só vez para que os utilizadores não interajam com outros elementos na página ao mesmo tempo.

Here's an example of how to setup route-based code splitting into your app using
libraries like [React Router](https://reacttraining.com/react-router/) with `React.lazy`.
Aqui está um exemplo de como configurar a divisão de código baseada nas rotas da aplicação através de bibliotecas como o [React Router](https://reacttraining.com/react-router/) com `React.lazy`.

```js
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
Expand All @@ -228,9 +193,9 @@ const App = () => (
);
```

## Named Exports {#named-exports}
## Exportações de nome {#named-exports}

`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 tree shaking keeps working and that you don't pull in unused components.
O `React.lazy`, atualmente, apenas suporta export default. Se o módulo que queres importar tem uma exportação de nome, então podes criar um módulo intermediário que tenha um export default. Assim garantes que o tree shaking continua a funcionar e não importa componentes não utilizados.
reinaldosimoes marked this conversation as resolved.
Show resolved Hide resolved

```js
// ManyComponents.js
Expand Down