Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translate "Code-Splitting" into Russian #246

Merged
merged 40 commits into from
Mar 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
34af8f7
Translate "Code-Splitting" into Russian
avevlad Mar 11, 2019
5285951
Typo fix "Code-Splitting" #246
avevlad Mar 12, 2019
505785e
Typo fix е -> ё "Code-Splitting" #246
avevlad Mar 12, 2019
81be3a0
Update content/docs/code-splitting.md
rlax Mar 13, 2019
ec9da5e
Update content/docs/code-splitting.md
rlax Mar 13, 2019
4675e42
Update content/docs/code-splitting.md
gcor Mar 13, 2019
d049c8a
Update content/docs/code-splitting.md
gcor Mar 13, 2019
9ae6895
Update content/docs/code-splitting.md
gcor Mar 13, 2019
cc3ee66
Update content/docs/code-splitting.md
gcor Mar 13, 2019
94f1219
Update content/docs/code-splitting.md
gcor Mar 13, 2019
6b50548
Update content/docs/code-splitting.md
gcor Mar 13, 2019
2627a7a
Update content/docs/code-splitting.md
gcor Mar 13, 2019
16c8d4a
Update content/docs/code-splitting.md
gcor Mar 13, 2019
af87cac
Update content/docs/code-splitting.md
gcor Mar 13, 2019
fe9a5dd
Update content/docs/code-splitting.md
gcor Mar 13, 2019
e9bbbbe
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
72067d9
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
3b07732
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
8967e86
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
060ba89
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
ffdd931
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
cd88754
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
c631fbc
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
3745a6d
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
5c4b54e
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
2035406
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
f59e2db
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
30d6888
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
2fef9b1
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
bec28ed
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
79b556f
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
64ce5f0
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
42dd234
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
29b83b7
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
dc82ecb
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
9a2217b
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
50dc272
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
6f48dc8
Update content/docs/code-splitting.md
another-guy Mar 14, 2019
cfbd4f3
формулировка "Бандлинг"
avevlad Mar 14, 2019
e280402
Задержка, ожидание загрузки
avevlad Mar 14, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 67 additions & 76 deletions content/docs/code-splitting.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
---
id: code-splitting
title: Code-Splitting
title: Разделение кода
permalink: docs/code-splitting.html
---

## Bundling {#bundling}
## Бандлинг {#bundling}

Most React apps will have their files "bundled" using tools like
[Webpack](https://webpack.js.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.
Большинство React-приложений «собирают» свои файлы такими инструментами, как
[Webpack](https://webpack.js.org/) или [Browserify](http://browserify.org/).
Сборка (или «бандлинг») — это процесс выявления импортированных файлов и объединения их в один «собранный» файл (часто называемый «bundle» или «бандл»).
Этот бандл после подключения на веб-страницу загружает всё приложение за один раз.

#### Example {#example}
#### Пример {#example}

**App:**
**Приложение:**

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

**Bundle:**
**Бандл:**

```js
function add(a, b) {
Expand All @@ -40,86 +39,82 @@ function add(a, b) {
console.log(add(16, 26)); // 42
```

> Note:
> Примечание:
>
> Your bundles will end up looking a lot different than this.
> Ваши бандлы будут выглядеть не так, как мы только что показали.

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.
Если вы используете [Create React App](https://github.com/facebookincubator/create-react-app), [Next.js](https://github.com/zeit/next.js/), [Gatsby](https://www.gatsbyjs.org/) или похожие инструменты, то у вас уже будет настроенный Webpack для бандлинга приложения.

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.
Иначе, вам нужно будет настроить webpack самостоятельно.
Для этого ознакомьтесь со страницами
[Установка](https://webpack.js.org/guides/installation/) и
[Начало работы](https://webpack.js.org/guides/getting-started/) в документации по Webpack.

## Code Splitting {#code-splitting}
## Разделение кода {#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.
Бандлинг это хорошо, но по мере роста вашего приложения, ваш бандл тоже будет расти.
Особенно если вы подключаете крупные сторонние библиотеки.
Вам нужно следить за кодом, который вы подключаете, чтобы случайно не сделать приложение настолько большим,
что его загрузка займёт слишком много времени.

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.
Чтобы предотвратить разрастание бандла, стоит начать «разделять» ваш бандл.
[Разделение кода](https://webpack.js.org/guides/code-splitting/) это возможность, поддерживаемая такими бандлерами
как Webpack или Browserify (с [factor-bundle](https://github.com/browserify/factor-bundle)), которая может создавать
несколько бандлов и загружать их по мере необходимости.

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.
Хоть вы и не уменьшите общий объём кода вашего приложения, но избежите загрузки кода, который
может никогда не понадобиться пользователю и уменьшите объём кода, необходимый для начальной загрузки.

## `import()` {#import}

The best way to introduce code-splitting into your app is through the dynamic
`import()` syntax.
Лучший способ внедрить разделение кода в приложение -- использовать синтаксис динамического импорта: `import()`.

**Before:**
**До:**

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

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

**After:**
**После:**

```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.
> Примечание:
>
> Синтаксис динамического импорта `import()` -- это ECMAScript (JavaScript)
> [предложение](https://github.com/tc39/proposal-dynamic-import),
> которое в данный момент не входит в стандарт языка. Ожидается, что он будет принят в ближайшем будущем.

Когда Webpack сталкивается с таким синтаксисом, он автоматически начинает разделять код вашего приложения.
Если вы используете Create React App, то всё уже настроено и
вы можете сразу [начать использовать](https://facebook.github.io/create-react-app/docs/code-splitting) синтаксис динамического импорта.
Он также поддерживается «из коробки» в [Next.js](https://github.com/zeit/next.js/#dynamic-import).

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).
Если вы настраиваете Webpack самостоятельно, то, вероятно, захотите прочитать [руководство Webpack по разделению кода](https://webpack.js.org/guides/code-splitting/).
Файл конфигурации Webpack должен выглядеть [примерно так](https://gist.github.com/gaearon/ca6e803f5c604d37468b0091d9959269).

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).
Если вы используете [Babel](https://babeljs.io/), вам необходимо убедиться, что он понимает синтаксис динамического импорта.
Для этого вам необходимо установить плагин [@babel/plugin-syntax-dynamic-import](https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import).

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

## `React.lazy` {#reactlazy}

> Note:
> Примечание:
>
> `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).
> Возможности `React.lazy` и задержки (suspense) пока недоступны для рендеринга на стороне сервера.
> Если вам нужно разделение кода в серверном приложении, мы рекомендуем [Loadable Components](https://github.com/smooth-code/loadable-components).
> У них есть хорошее [руководство по разделению бандла](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.
Функция `React.lazy` позволяет рендерить динамический импорт как обычный компонент.

**Before:**
**До:**

```js
import OtherComponent from './OtherComponent';
Expand All @@ -133,7 +128,7 @@ function MyComponent() {
}
```

**After:**
**После:**

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

This will automatically load the bundle containing the `OtherComponent` when this component gets rendered.
Она автоматически загрузит бандл содержащий `OtherComponent`, когда этот компонент будет отрендерен.

`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.
`React.lazy` принимает функцию, которая должна вызвать динамический `import()`. Результатом возвращённого Promise является модуль, который экспортирует по умолчанию React-компонент (`export default`).

### Suspense {#suspense}
### Задержка {#suspense}

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.
Если модуль, содержащий `OtherComponent`, ещё не загружен к моменту рендеринга `MyComponent`, пока ожидаем, мы должны показать запасное содержимое, например индикатор загрузки. Это можно сделать с помощью компонента `Suspense`.

```js
const OtherComponent = React.lazy(() => import('./OtherComponent'));
Expand All @@ -169,7 +164,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.
Проп `fallback` принимает любой React-элемент, который вы хотите показать, пока происходит загрузка компонента. Компонент `Suspense` можно разместить в любом месте над ленивым компонентом. Кроме того, можно обернуть несколько ленивых компонентов одним компонентом `Suspense`.

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

### Error boundaries {#error-boundaries}
### Предохранители {#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.

Если какой-то модуль не загружается (например, из-за сбоя сети), это вызовет ошибку. Вы можете обрабатывать эти ошибки для улучшения пользовательского опыта с помощью [Предохранителей](/docs/error-boundaries.html). После создания предохранителя, его можно использовать в любом месте над ленивыми компонентами для отображения состояния ошибки.

```js
import MyErrorBoundary from './MyErrorBoundary';
Expand All @@ -212,19 +208,14 @@ const MyComponent = () => (
);
```

## Route-based code splitting {#route-based-code-splitting}
## Разделение кода на основе маршрутов {#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.
Часто таким удобным местом оказываются маршруты. Большинство интернет-пользователей привыкли к задержкам во время переходов между страницами. Поэтому и вам может быть выгодно повторно отрендерить всю страницу целиком. Это не позволит пользователиям взаимодействовать с другими элементами на странице, пока происходит обновление.

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.
Вот пример того, как организовать разделение кода на основе маршрутов с помощью `React.lazy` и таких библиотек как [React Router](https://reacttraining.com/react-router/).

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

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

## Named Exports {#named-exports}
## Именованный экспорт {#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 treeshaking keeps working and that you don't pull in unused components.
`React.lazy` в настоящее время поддерживает только экспорт по умолчанию. Если модуль, который требуется импортировать, использует именованный экспорт, можно создать промежуточный модуль, который повторно экспортирует его как модуль по умолчанию. Это гарантирует работоспособность treeshaking -- механизма устранения неиспользуемого кода.

```js
// ManyComponents.js
Expand Down
2 changes: 1 addition & 1 deletion content/docs/nav.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
- id: accessibility
title: Accessibility
- id: code-splitting
title: Code-Splitting
title: Разделение кода
- id: context
title: Контекст
- id: error-boundaries
Expand Down