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
+66-75Lines changed: 66 additions & 75 deletions
Original file line number
Diff line number
Diff line change
@@ -1,20 +1,19 @@
1
1
---
2
2
id: code-splitting
3
-
title: Code-Splitting
3
+
title: Разделение кода
4
4
permalink: docs/code-splitting.html
5
5
---
6
6
7
-
## Bundling {#bundling}
7
+
## Бандлинг модулей {#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
+
Большинство React приложений собираются инструментами типа
10
+
[Webpack](https://webpack.js.org/) или [Browserify](http://browserify.org/) и состоят из нескольких "бандл" файлов.
11
+
Бандлинг -- это процесс группировки файлов с модулями и их зависимостями в один "бандл" файл.
12
+
Этот бандл после подключения на веб странице загружает всё приложение за один раз.
14
13
15
-
#### Example {#example}
14
+
#### Пример {#example}
16
15
17
-
**App:**
16
+
**Приложение:**
18
17
19
18
```js
20
19
// app.js
@@ -30,7 +29,7 @@ export function add(a, b) {
30
29
}
31
30
```
32
31
33
-
**Bundle:**
32
+
**Бандл:**
34
33
35
34
```js
36
35
functionadd(a, b) {
@@ -40,86 +39,82 @@ function add(a, b) {
40
39
console.log(add(16, 26)); // 42
41
40
```
42
41
43
-
> Note:
42
+
> Примечание:
44
43
>
45
-
> Your bundles will end up looking a lot different than this.
44
+
> Ваши бандлы будут выглядеть иначе, чем это.
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
+
Если вы используете [Create React App](https://github.com/facebookincubator/create-react-app), [Next.js](https://github.com/zeit/next.js/), [Gatsby](https://www.gatsbyjs.org/), или похожие инструменты, вы можете не задумываться о настройках, webpack там настроен из коробки.
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
+
Иначе, вам нужно будет настроить webpack самостоятельно.
> которое в данный момент не входит в стандарт языка. Ожидается, что он будет принят в ближайшем будущем.
93
+
94
+
Когда Webpack сталкивается с таким синтаксисом, он автоматически запускает разделение кода вашего приложения.
95
+
Если вы используете Create React App, то он уже настроен,
96
+
вы можете [начать использовать](https://facebook.github.io/create-react-app/docs/code-splitting) этот синтаксис прямо сейчас.
97
+
Он также поддерживается из коробки в [Next.js](https://github.com/zeit/next.js/#dynamic-import).
102
98
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://facebook.github.io/create-react-app/docs/code-splitting) immediately. It's also supported
106
-
out of the box in [Next.js](https://github.com/zeit/next.js/#dynamic-import).
99
+
Если вы настраиваете Webpack самостоятельно, то вероятно, вы захотите прочитать [руководство Webpack по разделению кода](https://webpack.js.org/guides/code-splitting/).
100
+
Ваш Webpack конфиг должен выглядеть [примерно так](https://gist.github.com/gaearon/ca6e803f5c604d37468b0091d9959269).
107
101
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).
102
+
Если вы используете [Babel](https://babeljs.io/), вам необходимо убедиться, что он понимает синтаксис динамического импорта.
103
+
Для этого вам необходимо установить плагин [@babel/plugin-syntax-dynamic-import](https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import).
110
104
111
-
When using [Babel](https://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).
113
105
114
106
## `React.lazy` {#reactlazy}
115
107
116
-
> Note:
108
+
> Примечание:
117
109
>
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).
110
+
> `React.lazy` и Suspense пока недоступны для рендеринга на стороне сервера.
111
+
> Если вам нужно разделение кода в серверном приложении, мы рекомендуем [Loadable Components](https://github.com/smooth-code/loadable-components).
112
+
> У них есть хорошее [руководство по разделению бандла](https://github.com/smooth-code/loadable-components/blob/master/packages/server/README.md) с серверным рендерингом.
113
+
119
114
120
-
The`React.lazy`function lets you render a dynamic import as a regular component.
115
+
Функция`React.lazy`позволяет рендерить динамический импорт как обычный компонент.
This will automatically load the bundle containing the `OtherComponent` when this component gets rendered.
145
+
Она автоматически загрузит бандл содержащий `OtherComponent`, когда этот компонент будет отрендерен.
151
146
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.
147
+
`React.lazy`принимает функцию, которая должна вызвать динамический `import()`.
153
148
154
149
### Suspense {#suspense}
155
150
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.
151
+
Если модуль, содержащий `OtherComponent`, еще не загружен к моменту рендеринга `MyComponent`, мы должны показать запасное содержимое, пока ожидаем загрузки, например индикатор загрузки. Это можно сделать с помощью компонента `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.
167
+
Этот`fallback`проп принимает любой React-элемент, который вы хотите показать во время ожидания загрузки компонента. Компонент `Suspense`можно разместить в любом месте над ленивым компонентом. Кроме того, можно обернуть несколько ленивых компонентов одним компонентом `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.
189
+
190
+
Если какой-то модуль не загружается (например, из-за сбоя сети), это вызовет ошибку. Вы можете обрабатывать эти ошибки ради хорошего пользовательского опыта с помощью [Предохранителей](/docs/error-boundaries.html). Создав предохранитель, вы можете использовать его в любом месте над ленивыми компонентами для отображения состояния ошибки.
## Разделение кода на основе маршрутов {#route-based-code-splitting}
212
+
213
+
Решение о том, где в вашем приложении ввести разделение кода, может быть немного сложным.
216
214
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.
215
+
Хороший вариант чтобы начать это -- маршруты. Большинство людей в интернете привыкли к переходам страниц, которые занимают некоторое время. Вы также склонны повторно рендерить всю страницу сразу, поэтому ваши пользователи вряд ли будут взаимодействовать с другими элементами на странице одновременно.
220
216
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.
217
+
Вот пример того, как организовать разделение кода на основе маршрутов в приложении с помощью библиотек, таких как [React Router](https://reacttraining.com/react-router/) с `React.lazy`.
225
218
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`.
`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.
241
+
`React.lazy`в настоящее время поддерживает только экспорт по умолчанию. Если модуль, который требуется импортировать, использует именованный экспорт, можно создать промежуточный модуль, который повторно экспортирует его как модуль по умолчанию. Это гарантирует что treeshaking будет работать.
0 commit comments