Skip to content

Commit ab6576b

Browse files
avevladanother-guy
authored andcommitted
Translate "Code-Splitting" into Russian
1 parent 293b4f6 commit ab6576b

File tree

2 files changed

+67
-76
lines changed

2 files changed

+67
-76
lines changed

content/docs/code-splitting.md

Lines changed: 66 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
---
22
id: code-splitting
3-
title: Code-Splitting
3+
title: Разделение кода
44
permalink: docs/code-splitting.html
55
---
66

7-
## Bundling {#bundling}
7+
## Бандлинг модулей {#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+
Большинство React приложений собираются инструментами типа
10+
[Webpack](https://webpack.js.org/) или [Browserify](http://browserify.org/) и состоят из нескольких "бандл" файлов.
11+
Бандлинг -- это процесс группировки файлов с модулями и их зависимостями в один "бандл" файл.
12+
Этот бандл после подключения на веб странице загружает всё приложение за один раз.
1413

15-
#### Example {#example}
14+
#### Пример {#example}
1615

17-
**App:**
16+
**Приложение:**
1817

1918
```js
2019
// app.js
@@ -30,7 +29,7 @@ export function add(a, b) {
3029
}
3130
```
3231

33-
**Bundle:**
32+
**Бандл:**
3433

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

43-
> Note:
42+
> Примечание:
4443
>
45-
> Your bundles will end up looking a lot different than this.
44+
> Ваши бандлы будут выглядеть иначе, чем это.
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+
Если вы используете [Create React App](https://github.com/facebookincubator/create-react-app), [Next.js](https://github.com/zeit/next.js/), [Gatsby](https://www.gatsbyjs.org/), или похожие инструменты, вы можете не задумываться о настройках, webpack там настроен из коробки.
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+
Иначе, вам нужно будет настроить webpack самостоятельно.
49+
Для этого ознакомьтесь со страницами
50+
[Установка](https://webpack.js.org/guides/installation/) и
51+
[Начала работы](https://webpack.js.org/guides/getting-started/) в документации по Webpack.
5452

55-
## Code Splitting {#code-splitting}
53+
## Разделение кода {#code-splitting}
5654

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.
55+
Бандлинг это отлично, но по мере того как ваше приложение растет, ваш бандл тоже растет.
56+
Особенно если вы подключаете крупные сторонние библиотеки.
57+
Вам нужно следить за тем что вы подключаете, чтобы случайно не сделать приложение настолько большим,
58+
что его загрузка займет слишком много времени.
6159

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

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

7568
## `import()` {#import}
7669

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

80-
**Before:**
72+
**До:**
8173

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

8577
console.log(add(16, 26));
8678
```
8779

88-
**After:**
80+
**После:**
8981

9082
```js
9183
import("./math").then(math => {
9284
console.log(math.add(16, 26));
9385
});
9486
```
9587

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

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

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

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

114106
## `React.lazy` {#reactlazy}
115107

116-
> Note:
108+
> Примечание:
117109
>
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+
119114

120-
The `React.lazy` function lets you render a dynamic import as a regular component.
115+
Функция `React.lazy` позволяет рендерить динамический импорт как обычный компонент.
121116

122-
**Before:**
117+
**До:**
123118

124119
```js
125120
import OtherComponent from './OtherComponent';
@@ -133,7 +128,7 @@ function MyComponent() {
133128
}
134129
```
135130

136-
**After:**
131+
**После:**
137132

138133
```js
139134
const OtherComponent = React.lazy(() => import('./OtherComponent'));
@@ -147,13 +142,13 @@ function MyComponent() {
147142
}
148143
```
149144

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

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()`.
153148

154149
### Suspense {#suspense}
155150

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

158153
```js
159154
const OtherComponent = React.lazy(() => import('./OtherComponent'));
@@ -169,7 +164,7 @@ function MyComponent() {
169164
}
170165
```
171166

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.
167+
Этот `fallback` проп принимает любой React-элемент, который вы хотите показать во время ожидания загрузки компонента. Компонент `Suspense` можно разместить в любом месте над ленивым компонентом. Кроме того, можно обернуть несколько ленивых компонентов одним компонентом `Suspense`.
173168

174169
```js
175170
const OtherComponent = React.lazy(() => import('./OtherComponent'));
@@ -189,9 +184,10 @@ function MyComponent() {
189184
}
190185
```
191186

192-
### Error boundaries {#error-boundaries}
187+
### Предохранители (компоненты Error Boundary) {#error-boundaries}
193188

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.
189+
190+
Если какой-то модуль не загружается (например, из-за сбоя сети), это вызовет ошибку. Вы можете обрабатывать эти ошибки ради хорошего пользовательского опыта с помощью [Предохранителей](/docs/error-boundaries.html). Создав предохранитель, вы можете использовать его в любом месте над ленивыми компонентами для отображения состояния ошибки.
195191

196192
```js
197193
import MyErrorBoundary from './MyErrorBoundary';
@@ -212,19 +208,14 @@ const MyComponent = () => (
212208
);
213209
```
214210

215-
## Route-based code splitting {#route-based-code-splitting}
211+
## Разделение кода на основе маршрутов {#route-based-code-splitting}
212+
213+
Решение о том, где в вашем приложении ввести разделение кода, может быть немного сложным.
216214

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

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

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

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

248-
## Named Exports {#named-exports}
239+
## Именованный Экспорт {#named-exports}
249240

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.
241+
`React.lazy` в настоящее время поддерживает только экспорт по умолчанию. Если модуль, который требуется импортировать, использует именованный экспорт, можно создать промежуточный модуль, который повторно экспортирует его как модуль по умолчанию. Это гарантирует что treeshaking будет работать.
251242

252243
```js
253244
// ManyComponents.js

content/docs/nav.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
- id: accessibility
4141
title: Доступность контента
4242
- id: code-splitting
43-
title: Code-Splitting
43+
title: Разделение кода
4444
- id: context
4545
title: Контекст
4646
- id: error-boundaries

0 commit comments

Comments
 (0)