diff --git a/src/content/learn/react-compiler.md b/src/content/learn/react-compiler.md
index 9d4e19d210..fa9411420b 100644
--- a/src/content/learn/react-compiler.md
+++ b/src/content/learn/react-compiler.md
@@ -3,66 +3,66 @@ title: React Compiler
---
-This page will give you an introduction to React Compiler and how to try it out successfully.
+Эта страница даст вам введение в React Compiler и расскажет, как успешно его попробовать.
-* Getting started with the compiler
-* Installing the compiler and ESLint plugin
-* Troubleshooting
+* Начало работы с компилятором
+* Установка компилятора и плагина ESLint
+* Устранение неполадок
-React Compiler is a new compiler currently in RC, that we've open sourced to get feedback from the community. We now recommend everyone to try the compiler and provide feedback.
+React Compiler — это новый компилятор, находящийся в стадии RC (Release Candidate), который мы сделали с открытым исходным кодом для получения обратной связи от сообщества. Мы теперь рекомендуем всем попробовать компилятор и предоставить свои отзывы.
-The latest RC release can be found with the `@rc` tag, and daily experimental releases with `@experimental`.
+Последний RC-релиз можно найти с тегом `@rc`, а ежедневные экспериментальные релизы — с тегом `@experimental`.
-React Compiler is a new compiler that we've open sourced to get feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it.
+React Compiler — это новый компилятор, который мы сделали с открытым исходным кодом для получения обратной связи от сообщества. Это инструмент, работающий только на этапе сборки, который автоматически оптимизирует ваше React-приложение. Он работает с обычным JavaScript и понимает [Правила React](/reference/rules), поэтому вам не нужно переписывать код, чтобы использовать его.
-eslint-plugin-react-hooks also includes an [ESLint rule](#installing-eslint-plugin-react-compiler) that surfaces the analysis from the compiler right in your editor. **We strongly recommend everyone use the linter today.** The linter does not require that you have the compiler installed, so you can use it even if you are not ready to try out the compiler.
+`eslint-plugin-react-hooks` также включает [правило ESLint](#installing-eslint-plugin-react-compiler), которое отображает анализ компилятора прямо в вашем редакторе. **Мы настоятельно рекомендуем всем использовать линтер уже сегодня.** Линтер не требует установки компилятора, поэтому вы можете использовать его, даже если вы еще не готовы попробовать сам компилятор.
-The compiler is currently released as `rc`, and is available to try out on React 17+ apps and libraries. To install the RC:
+В настоящее время компилятор выпускается под тегом `rc` и доступен для тестирования в приложениях и библиотеках React 17+. Чтобы установить RC:
{`npm install -D babel-plugin-react-compiler@rc eslint-plugin-react-hooks@^6.0.0-rc.1`}
-Or, if you're using Yarn:
+Или, если вы используете Yarn:
{`yarn add -D babel-plugin-react-compiler@rc eslint-plugin-react-hooks@^6.0.0-rc.1`}
-If you are not using React 19 yet, please see [the section below](#using-react-compiler-with-react-17-or-18) for further instructions.
+Если вы еще не используете React 19, пожалуйста, обратитесь к [разделу ниже](#using-react-compiler-with-react-17-or-18) для получения дальнейших инструкций.
-### What does the compiler do? {/*what-does-the-compiler-do*/}
+### Что делает компилятор? {/*what-does-the-compiler-do*/}
-In order to optimize applications, React Compiler automatically memoizes your code. You may be familiar today with memoization through APIs such as `useMemo`, `useCallback`, and `React.memo`. With these APIs you can tell React that certain parts of your application don't need to recompute if their inputs haven't changed, reducing work on updates. While powerful, it's easy to forget to apply memoization or apply them incorrectly. This can lead to inefficient updates as React has to check parts of your UI that don't have any _meaningful_ changes.
+Для оптимизации приложений React Compiler автоматически мемоизирует ваш код. Возможно, вы уже знакомы с мемоизацией через такие API, как `useMemo`, `useCallback` и `React.memo`. С помощью этих API вы можете сообщить React, что определенные части вашего приложения не нуждаются в перерасчете, если их входные данные не изменились, уменьшая нагрузку при обновлениях. Хотя это и мощно, легко забыть применить мемоизацию или применить ее неправильно. Это может привести к неэффективным обновлениям, поскольку React приходится проверять части вашего UI, которые не имеют _значимых_ изменений.
-The compiler uses its knowledge of JavaScript and React's rules to automatically memoize values or groups of values within your components and hooks. If it detects breakages of the rules, it will automatically skip over just those components or hooks, and continue safely compiling other code.
+Компилятор использует свои знания JavaScript и правил React для автоматической мемоизации значений или групп значений внутри ваших компонентов и хуков. Если он обнаруживает нарушения правил, он автоматически пропускает только те компоненты или хуки и безопасно продолжает компилировать другой код.
-React Compiler can statically detect when Rules of React are broken, and safely opt-out of optimizing just the affected components or hooks. It is not necessary for the compiler to optimize 100% of your codebase.
+React Compiler может статически определять, когда нарушаются Правила React, и безопасно отказываться от оптимизации только затронутых компонентов или хуков. Компилятору не обязательно оптимизировать 100% вашей кодовой базы.
-If your codebase is already very well-memoized, you might not expect to see major performance improvements with the compiler. However, in practice memoizing the correct dependencies that cause performance issues is tricky to get right by hand.
+Если ваша кодовая база уже хорошо мемоизирована, вы можете не ожидать значительного улучшения производительности с помощью компилятора. Однако на практике мемоизировать правильные зависимости, вызывающие проблемы с производительностью, сложно сделать вручную.
-#### What kind of memoization does React Compiler add? {/*what-kind-of-memoization-does-react-compiler-add*/}
+#### Какую мемоизацию добавляет React Compiler? {/*what-kind-of-memoization-does-react-compiler-add*/}
-The initial release of React Compiler is primarily focused on **improving update performance** (re-rendering existing components), so it focuses on these two use cases:
+Первый выпуск React Compiler в основном сосредоточен на **улучшении производительности обновлений** (повторного рендеринга существующих компонентов), поэтому он фокусируется на этих двух сценариях использования:
-1. **Skipping cascading re-rendering of components**
- * Re-rendering `` causes many components in its component tree to re-render, even though only `` has changed
-1. **Skipping expensive calculations from outside of React**
- * For example, calling `expensivelyProcessAReallyLargeArrayOfObjects()` inside of your component or hook that needs that data
+1. **Пропуск каскадного повторного рендеринга компонентов**
+ * Повторный рендеринг `` вызывает повторный рендеринг многих компонентов в его дереве компонентов, даже если изменился только ``
+1. **Пропуск дорогостоящих вычислений извне React**
+ * Например, вызов `expensivelyProcessAReallyLargeArrayOfObjects()` внутри вашего компонента или хука, которому нужны эти данные
-#### Optimizing Re-renders {/*optimizing-re-renders*/}
+#### Оптимизация повторных рендеров {/*optimizing-re-renders*/}
-React lets you express your UI as a function of their current state (more concretely: their props, state, and context). In its current implementation, when a component's state changes, React will re-render that component _and all of its children_ — unless you have applied some form of manual memoization with `useMemo()`, `useCallback()`, or `React.memo()`. For example, in the following example, `` will re-render whenever ``'s state changes:
+React позволяет вам выражать ваш UI как функцию от текущего состояния (точнее: их пропсов, состояния и контекста). В текущей реализации, когда состояние компонента изменяется, React будет повторно рендерить этот компонент _и всех его дочерних элементов_ — если вы не применили какую-либо форму ручной мемоизации с помощью `useMemo()`, `useCallback()` или `React.memo()`. Например, в следующем примере `` будет повторно рендериться всякий раз, когда изменяется состояние ``:
```javascript
function FriendList({ friends }) {
@@ -81,67 +81,67 @@ function FriendList({ friends }) {
);
}
```
-[_See this example in the React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEAYjHgpgCYAyeYOAFMEWuZVWEQL4CURwADrEicQgyKEANnkwIAwtEw4iAXiJQwCMhWoB5TDLmKsTXgG5hRInjRFGbXZwB0UygHMcACzWr1ABn4hEWsYBBxYYgAeADkIHQ4uAHoAPksRbisiMIiYYkYs6yiqPAA3FMLrIiiwAAcAQ0wU4GlZBSUcbklDNqikusaKkKrgR0TnAFt62sYHdmp+VRT7SqrqhOo6Bnl6mCoiAGsEAE9VUfmqZzwqLrHqM7ubolTVol5eTOGigFkEMDB6u4EAAhKA4HCEZ5DNZ9ErlLIWYTcEDcIA)
+[_См. этот пример в React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEAYjHgpgCYAyeYOAFMEWuZVWEQL4CURwADrEicQgyKEANnkwIAwtEw4iAXiJQwCMhWoB5TDLmKsTXgG5hRInjRFGbXZwB0UygHMcACzWr1ABn4hEWsYBBxYYgAeADkIHQ4uAHoAPksRbisiMIiYYkYs6yiqPAA3FMLrIiiwAAcAQ0wU4GlZBSUcbklDNqikusaKkKrgR0TnAFt62sYHdmp+VRT7SqrqhOo6Bnl6mCoiAGsEAE9VUfmqZzwqLrHqM7ubolTVol5eTOGigFkEMDB6u4EAAhKA4HCEZ5DNZ9ErlLIWYTcEDcIA)
-React Compiler automatically applies the equivalent of manual memoization, ensuring that only the relevant parts of an app re-render as state changes, which is sometimes referred to as "fine-grained reactivity". In the above example, React Compiler determines that the return value of `` can be reused even as `friends` changes, and can avoid recreating this JSX _and_ avoid re-rendering `` as the count changes.
+React Compiler автоматически применяет эквивалент ручной мемоизации, гарантируя, что только соответствующие части приложения повторно рендерятся при изменении состояния, что иногда называют "мелкозернистой реактивностью". В приведенном выше примере React Compiler определяет, что возвращаемое значение `` может быть повторно использовано даже при изменении `friends`, и может избежать воссоздания этого JSX _и_ избежать повторного рендеринга `` при изменении счетчика.
-#### Expensive calculations also get memoized {/*expensive-calculations-also-get-memoized*/}
+#### Дорогостоящие вычисления также мемоизируются {/*expensive-calculations-also-get-memoized*/}
-The compiler can also automatically memoize for expensive calculations used during rendering:
+Компилятор также может автоматически мемоизировать дорогостоящие вычисления, используемые во время рендеринга:
```js
-// **Not** memoized by React Compiler, since this is not a component or hook
+// **Не** мемоизируется React Compiler, так как это не компонент и не хук
function expensivelyProcessAReallyLargeArrayOfObjects() { /* ... */ }
-// Memoized by React Compiler since this is a component
+// Мемоизируется React Compiler, так как это компонент
function TableContainer({ items }) {
- // This function call would be memoized:
+ // Этот вызов функции будет мемоизирован:
const data = expensivelyProcessAReallyLargeArrayOfObjects(items);
// ...
}
```
-[_See this example in the React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAejQAgFTYHIQAuumAtgqRAJYBeCAJpgEYCemASggIZyGYDCEUgAcqAGwQwANJjBUAdokyEAFlTCZ1meUUxdMcIcIjyE8vhBiYVECAGsAOvIBmURYSonMCAB7CzcgBuCGIsAAowEIhgYACCnFxioQAyXDAA5gixMDBcLADyzvlMAFYIvGAAFACUmMCYaNiYAHStOFgAvk5OGJgAshTUdIysHNy8AkbikrIKSqpaWvqGIiZmhE6u7p7ymAAqXEwSguZcCpKV9VSEFBodtcBOmAYmYHz0XIT6ALzefgFUYKhCJRBAxeLcJIsVIZLI5PKFYplCqVa63aoAbm6u0wMAQhFguwAPPRAQA+YAfL4dIloUmBMlODogDpAA)
+[_См. этот пример в React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAejQAgFTYHIQAuumAtgqRAJYBeCAJpgEYCemASggIZyGYDCEUgAcqAGwQwANJjBUAdokyEAFlTCZ1meUUxdMcIcIjyE8vhBiYVECAGsAOvIBmURYSonMCAB7CzcgBuCGIsAAowEIhgYACCnFxioQAyXDAA5gixMDBcLADyzvlMAFYIvGAAFACUmMCYaNiYAHStOFgAvk5OGJgAshTUdIysHNy8AkbikrIKSqpaWvqGIiZmhE6u7p7ymAAqXEwSguZcCpKV9VSEFBodtcBOmAYmYHz0XIT6ALzefgFUYKhCJRBAxeLcJIsVIZLI5PKFYplCqVa63aoAbm6u0wMAQhFguwAPPRAQA+YAfL4dIloUmBMlODogDpAA)
-However, if `expensivelyProcessAReallyLargeArrayOfObjects` is truly an expensive function, you may want to consider implementing its own memoization outside of React, because:
+Однако, если `expensivelyProcessAReallyLargeArrayOfObjects` действительно является дорогостоящей функцией, вам может потребоваться рассмотреть возможность реализации собственной мемоизации вне React, потому что:
-- React Compiler only memoizes React components and hooks, not every function
-- React Compiler's memoization is not shared across multiple components or hooks
+- React Compiler мемоизирует только React-компоненты и хуки, а не каждую функцию.
+- Мемоизация React Compiler не разделяется между несколькими компонентами или хуками.
-So if `expensivelyProcessAReallyLargeArrayOfObjects` was used in many different components, even if the same exact items were passed down, that expensive calculation would be run repeatedly. We recommend [profiling](https://react.dev/reference/react/useMemo#how-to-tell-if-a-calculation-is-expensive) first to see if it really is that expensive before making code more complicated.
+Таким образом, если `expensivelyProcessAReallyLargeArrayOfObjects` использовалась во многих различных компонентах, даже если передавались одни и те же элементы, это дорогостоящее вычисление будет выполняться повторно. Мы рекомендуем сначала [профилировать](https://react.dev/reference/react/useMemo#how-to-tell-if-a-calculation-is-expensive), чтобы узнать, действительно ли оно настолько дорогостоящее, прежде чем усложнять код.
-### Should I try out the compiler? {/*should-i-try-out-the-compiler*/}
+### Стоит ли пробовать компилятор? {/*should-i-try-out-the-compiler*/}
-The compiler is now in RC and has been tested extensively in production. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules).
+Компилятор сейчас находится в стадии RC и был тщательно протестирован в продакшене. Хотя он использовался в продакшене в таких компаниях, как Meta, внедрение компилятора в продакшен для вашего приложения будет зависеть от состояния вашей кодовой базы и того, насколько хорошо вы следовали [Правилам React](/reference/rules).
-**You don't have to rush into using the compiler now. It's okay to wait until it reaches a stable release before adopting it.** However, we do appreciate trying it out in small experiments in your apps so that you can [provide feedback](#reporting-issues) to us to help make the compiler better.
+**Вам не нужно спешить с использованием компилятора сейчас. Вы можете подождать, пока он достигнет стабильного релиза, прежде чем внедрять его.** Однако мы будем признательны, если вы попробуете его в небольших экспериментах в ваших приложениях, чтобы вы могли [предоставить нам обратную связь](#reporting-issues) и помочь улучшить компилятор.
-## Getting Started {/*getting-started*/}
+## Начало работы {/*getting-started*/}
-In addition to these docs, we recommend checking the [React Compiler Working Group](https://github.com/reactwg/react-compiler) for additional information and discussion about the compiler.
+В дополнение к этой документации мы рекомендуем ознакомиться с [Рабочей группой React Compiler](https://github.com/reactwg/react-compiler) для получения дополнительной информации и обсуждения компилятора.
-### Installing eslint-plugin-react-hooks {/*installing-eslint-plugin-react-compiler*/}
+### Установка eslint-plugin-react-hooks {/*installing-eslint-plugin-react-compiler*/}
-React Compiler also powers an ESLint plugin. You can try it out by installing eslint-plugin-react-hooks@^6.0.0-rc.1.
+React Compiler также включает в себя плагин ESLint. Вы можете попробовать его, установив `eslint-plugin-react-hooks@^6.0.0-rc.1`.
{`npm install -D eslint-plugin-react-hooks@^6.0.0-rc.1`}
-See our [editor setup](/learn/editor-setup#linting) guide for more details.
+См. наше руководство по [настройке редактора](/learn/editor-setup#linting) для получения более подробной информации.
-The ESLint plugin will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase.
+Плагин ESLint будет отображать любые нарушения правил React в вашем редакторе. Когда это происходит, это означает, что компилятор пропустил оптимизацию этого компонента или хука. Это совершенно нормально, и компилятор может восстановиться и продолжить оптимизацию других компонентов в вашей кодовой базе.
-**You don't have to fix all ESLint violations straight away.** You can address them at your own pace to increase the amount of components and hooks being optimized, but it is not required to fix everything before you can use the compiler.
+**Вам не нужно исправлять все нарушения ESLint сразу.** Вы можете исправлять их в своем темпе, чтобы увеличить количество оптимизируемых компонентов и хуков, но это не требуется для использования компилятора.
-### Rolling out the compiler to your codebase {/*using-the-compiler-effectively*/}
+### Развертывание компилятора в вашей кодовой базе {/*using-the-compiler-effectively*/}
-#### Existing projects {/*existing-projects*/}
-The compiler is designed to compile functional components and hooks that follow the [Rules of React](/reference/rules). It can also handle code that breaks those rules by bailing out (skipping over) those components or hooks. However, due to the flexible nature of JavaScript, the compiler cannot catch every possible violation and may compile with false negatives: that is, the compiler may accidentally compile a component/hook that breaks the Rules of React which can lead to undefined behavior.
+#### Существующие проекты {/*existing-projects*/}
+Компилятор предназначен для компиляции функциональных компонентов и хуков, которые следуют [Правилам React](/reference/rules). Он также может обрабатывать код, нарушающий эти правила, путем выхода (пропуска) этих компонентов или хуков. Однако из-за гибкой природы JavaScript компилятор не может обнаружить каждое возможное нарушение и может компилировать с ложными отрицаниями: то есть компилятор может случайно скомпилировать компонент/хук, нарушающий Правила React, что может привести к неопределенному поведению.
-For this reason, to adopt the compiler successfully on existing projects, we recommend running it on a small directory in your product code first. You can do this by configuring the compiler to only run on a specific set of directories:
+По этой причине, чтобы успешно внедрить компилятор в существующие проекты, мы рекомендуем сначала запустить его в небольшом каталоге вашего продуктового кода. Вы можете сделать это, настроив компилятор так, чтобы он работал только в определенном наборе каталогов:
```js {3}
const ReactCompilerConfig = {
@@ -151,21 +151,21 @@ const ReactCompilerConfig = {
};
```
-When you have more confidence with rolling out the compiler, you can expand coverage to other directories as well and slowly roll it out to your whole app.
+Когда вы будете более уверены в развертывании компилятора, вы сможете расширить охват на другие каталоги и постепенно развернуть его на все ваше приложение.
-#### New projects {/*new-projects*/}
+#### Новые проекты {/*new-projects*/}
-If you're starting a new project, you can enable the compiler on your entire codebase, which is the default behavior.
+Если вы начинаете новый проект, вы можете включить компилятор для всей вашей кодовой базы, что является поведением по умолчанию.
-### Using React Compiler with React 17 or 18 {/*using-react-compiler-with-react-17-or-18*/}
+### Использование React Compiler с React 17 или 18 {/*using-react-compiler-with-react-17-or-18*/}
-React Compiler works best with React 19 RC. If you are unable to upgrade, you can install the extra `react-compiler-runtime` package which will allow the compiled code to run on versions prior to 19. However, note that the minimum supported version is 17.
+React Compiler лучше всего работает с React 19 RC. Если вы не можете обновиться, вы можете установить дополнительный пакет `react-compiler-runtime`, который позволит скомпилированному коду работать в версиях до 19. Однако обратите внимание, что минимальная поддерживаемая версия — 17.
{`npm install react-compiler-runtime@rc`}
-You should also add the correct `target` to your compiler config, where `target` is the major version of React you are targeting:
+Вам также следует добавить правильный `target` в вашу конфигурацию компилятора, где `target` — это основная версия React, на которую вы ориентируетесь:
```js {3}
// babel.config.js
@@ -182,17 +182,17 @@ module.exports = function () {
};
```
-### Using the compiler on libraries {/*using-the-compiler-on-libraries*/}
+### Использование компилятора для библиотек {/*using-the-compiler-on-libraries*/}
-React Compiler can also be used to compile libraries. Because React Compiler needs to run on the original source code prior to any code transformations, it is not possible for an application's build pipeline to compile the libraries they use. Hence, our recommendation is for library maintainers to independently compile and test their libraries with the compiler, and ship compiled code to npm.
+React Compiler также можно использовать для компиляции библиотек. Поскольку React Compiler должен работать с исходным кодом до любых преобразований кода, конвейер сборки приложения не может компилировать используемые им библиотеки. Поэтому мы рекомендуем сопровождающим библиотек самостоятельно компилировать и тестировать свои библиотеки с помощью компилятора и публиковать скомпилированный код в npm.
-Because your code is pre-compiled, users of your library will not need to have the compiler enabled in order to benefit from the automatic memoization applied to your library. If your library targets apps not yet on React 19, specify a minimum [`target` and add `react-compiler-runtime` as a direct dependency](#using-react-compiler-with-react-17-or-18). The runtime package will use the correct implementation of APIs depending on the application's version, and polyfill the missing APIs if necessary.
+Поскольку ваш код предварительно скомпилирован, пользователям вашей библиотеки не потребуется включать компилятор, чтобы воспользоваться преимуществами автоматической мемоизации, примененной к вашей библиотеке. Если ваша библиотека ориентирована на приложения, которые еще не используют React 19, укажите минимальный [`target` и добавьте `react-compiler-runtime` в качестве прямой зависимости](#using-react-compiler-with-react-17-or-18). Пакет среды выполнения будет использовать правильную реализацию API в зависимости от версии приложения и полифиллить отсутствующие API при необходимости.
-Library code can often require more complex patterns and usage of escape hatches. For this reason, we recommend ensuring that you have sufficient testing in order to identify any issues that might arise from using the compiler on your library. If you identify any issues, you can always opt-out the specific components or hooks with the [`'use no memo'` directive](#something-is-not-working-after-compilation).
+Код библиотеки часто может требовать более сложных шаблонов и использования обходных путей. По этой причине мы рекомендуем убедиться, что у вас достаточно тестирования, чтобы выявить любые проблемы, которые могут возникнуть при использовании компилятора для вашей библиотеки. Если вы выявите какие-либо проблемы, вы всегда можете исключить конкретные компоненты или хуки с помощью директивы [`'use no memo'`](#something-is-not-working-after-compilation).
-Similarly to apps, it is not necessary to fully compile 100% of your components or hooks to see benefits in your library. A good starting point might be to identify the most performance sensitive parts of your library and ensuring that they don't break the [Rules of React](/reference/rules), which you can use `eslint-plugin-react-compiler` to identify.
+Аналогично приложениям, не обязательно полностью компилировать 100% ваших компонентов или хуков, чтобы увидеть преимущества в вашей библиотеке. Хорошей отправной точкой может быть выявление наиболее чувствительных к производительности частей вашей библиотеки и обеспечение того, чтобы они не нарушали [Правила React](/reference/rules), для выявления которых вы можете использовать `eslint-plugin-react-compiler`.
-## Usage {/*installation*/}
+## Использование {/*installation*/}
### Babel {/*usage-with-babel*/}
@@ -200,9 +200,9 @@ Similarly to apps, it is not necessary to fully compile 100% of your components
{`npm install babel-plugin-react-compiler@rc`}
-The compiler includes a Babel plugin which you can use in your build pipeline to run the compiler.
+Компилятор включает в себя плагин Babel, который вы можете использовать в своем конвейере сборки для запуска компилятора.
-After installing, add it to your Babel config. Please note that it's critical that the compiler run **first** in the pipeline:
+После установки добавьте его в свою конфигурацию Babel. Обратите внимание, что крайне важно, чтобы компилятор запускался **первым** в конвейере:
```js {7}
// babel.config.js
@@ -211,18 +211,18 @@ const ReactCompilerConfig = { /* ... */ };
module.exports = function () {
return {
plugins: [
- ['babel-plugin-react-compiler', ReactCompilerConfig], // must run first!
+ ['babel-plugin-react-compiler', ReactCompilerConfig], // должен запускаться первым!
// ...
],
};
};
```
-`babel-plugin-react-compiler` should run first before other Babel plugins as the compiler requires the input source information for sound analysis.
+`babel-plugin-react-compiler` должен запускаться перед другими плагинами Babel, поскольку компилятору требуется информация об исходном коде для корректного анализа.
### Vite {/*usage-with-vite*/}
-If you use Vite, you can add the plugin to vite-plugin-react:
+Если вы используете Vite, вы можете добавить плагин в `vite-plugin-react`:
```js {10}
// vite.config.js
@@ -246,10 +246,10 @@ export default defineConfig(() => {
### Next.js {/*usage-with-nextjs*/}
-Please refer to the [Next.js docs](https://nextjs.org/docs/app/api-reference/next-config-js/reactCompiler) for more information.
+Пожалуйста, обратитесь к [документации Next.js](https://nextjs.org/docs/app/api-reference/next-config-js/reactCompiler) для получения дополнительной информации.
### Remix {/*usage-with-remix*/}
-Install `vite-plugin-babel`, and add the compiler's Babel plugin to it:
+Установите `vite-plugin-babel` и добавьте в него плагин Babel компилятора:
{`npm install vite-plugin-babel`}
@@ -267,7 +267,7 @@ export default defineConfig({
babel({
filter: /\.[jt]sx?$/,
babelConfig: {
- presets: ["@babel/preset-typescript"], // if you use TypeScript
+ presets: ["@babel/preset-typescript"], // если вы используете TypeScript
plugins: [
["babel-plugin-react-compiler", ReactCompilerConfig],
],
@@ -279,54 +279,54 @@ export default defineConfig({
### Webpack {/*usage-with-webpack*/}
-A community webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack).
+Загрузчик от сообщества для Webpack [теперь доступен здесь](https://github.com/SukkaW/react-compiler-webpack).
### Expo {/*usage-with-expo*/}
-Please refer to [Expo's docs](https://docs.expo.dev/guides/react-compiler/) to enable and use the React Compiler in Expo apps.
+Пожалуйста, обратитесь к [документации Expo](https://docs.expo.dev/guides/react-compiler/), чтобы включить и использовать React Compiler в приложениях Expo.
### Metro (React Native) {/*usage-with-react-native-metro*/}
-React Native uses Babel via Metro, so refer to the [Usage with Babel](#usage-with-babel) section for installation instructions.
+React Native использует Babel через Metro, поэтому обратитесь к разделу [Использование с Babel](#usage-with-babel) для получения инструкций по установке.
### Rspack {/*usage-with-rspack*/}
-Please refer to [Rspack's docs](https://rspack.dev/guide/tech/react#react-compiler) to enable and use the React Compiler in Rspack apps.
+Пожалуйста, обратитесь к [документации Rspack](https://rspack.dev/guide/tech/react#react-compiler), чтобы включить и использовать React Compiler в приложениях Rspack.
### Rsbuild {/*usage-with-rsbuild*/}
-Please refer to [Rsbuild's docs](https://rsbuild.dev/guide/framework/react#react-compiler) to enable and use the React Compiler in Rsbuild apps.
+Пожалуйста, обратитесь к [документации Rsbuild](https://rsbuild.dev/guide/framework/react#react-compiler), чтобы включить и использовать React Compiler в приложениях Rsbuild.
-## Troubleshooting {/*troubleshooting*/}
+## Устранение неполадок {/*troubleshooting*/}
-To report issues, please first create a minimal repro on the [React Compiler Playground](https://playground.react.dev/) and include it in your bug report. You can open issues in the [facebook/react](https://github.com/facebook/react/issues) repo.
+Чтобы сообщить о проблемах, сначала создайте минимальный воспроизводимый пример на [React Compiler Playground](https://playground.react.dev/) и включите его в свой отчет об ошибке. Вы можете открывать проблемы в репозитории [facebook/react](https://github.com/facebook/react/issues).
-You can also provide feedback in the React Compiler Working Group by applying to be a member. Please see [the README for more details on joining](https://github.com/reactwg/react-compiler).
+Вы также можете предоставить обратную связь в Рабочей группе React Compiler, подав заявку на членство. Пожалуйста, см. [README для получения более подробной информации о присоединении](https://github.com/reactwg/react-compiler).
-### What does the compiler assume? {/*what-does-the-compiler-assume*/}
+### На что полагается компилятор? {/*what-does-the-compiler-assume*/}
-React Compiler assumes that your code:
+React Compiler предполагает, что ваш код:
-1. Is valid, semantic JavaScript.
-2. Tests that nullable/optional values and properties are defined before accessing them (for example, by enabling [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) if using TypeScript), i.e., `if (object.nullableProperty) { object.nullableProperty.foo }` or with optional-chaining `object.nullableProperty?.foo`.
-3. Follows the [Rules of React](https://react.dev/reference/rules).
+1. Является допустимым, семантическим JavaScript.
+2. Проверяет, что нулевые/необязательные значения и свойства определены перед их доступом (например, путем включения [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) при использовании TypeScript), т. е. `if (object.nullableProperty) { object.nullableProperty.foo }` или с помощью опциональной цепочки `object.nullableProperty?.foo`.
+3. Соответствует [Правилам React](https://react.dev/reference/rules).
-React Compiler can verify many of the Rules of React statically, and will safely skip compilation when it detects an error. To see the errors we recommend also installing [eslint-plugin-react-compiler](https://www.npmjs.com/package/eslint-plugin-react-compiler).
+React Compiler может статически проверять многие Правила React и безопасно пропускать компиляцию при обнаружении ошибки. Чтобы увидеть ошибки, мы рекомендуем также установить [eslint-plugin-react-compiler](https://www.npmjs.com/package/eslint-plugin-react-compiler).
-### How do I know my components have been optimized? {/*how-do-i-know-my-components-have-been-optimized*/}
+### Как узнать, были ли мои компоненты оптимизированы? {/*how-do-i-know-my-components-have-been-optimized*/}
-[React DevTools](/learn/react-developer-tools) (v5.0+) and [React Native DevTools](https://reactnative.dev/docs/react-native-devtools) have built-in support for React Compiler and will display a "Memo ✨" badge next to components that have been optimized by the compiler.
+[React DevTools](/learn/react-developer-tools) (v5.0+) и [React Native DevTools](https://reactnative.dev/docs/react-native-devtools) имеют встроенную поддержку React Compiler и будут отображать значок "Memo ✨" рядом с компонентами, которые были оптимизированы компилятором.
-### Something is not working after compilation {/*something-is-not-working-after-compilation*/}
-If you have eslint-plugin-react-compiler installed, the compiler will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase. **You don't have to fix all ESLint violations straight away.** You can address them at your own pace to increase the amount of components and hooks being optimized.
+### Что-то не работает после компиляции {/*something-is-not-working-after-compilation*/}
+Если у вас установлен `eslint-plugin-react-compiler`, компилятор будет отображать любые нарушения правил React в вашем редакторе. Когда это происходит, это означает, что компилятор пропустил оптимизацию этого компонента или хука. Это совершенно нормально, и компилятор может восстановиться и продолжить оптимизацию других компонентов в вашей кодовой базе. **Вам не нужно исправлять все нарушения ESLint сразу.** Вы можете исправлять их в своем темпе, чтобы увеличить количество оптимизируемых компонентов и хуков.
-Due to the flexible and dynamic nature of JavaScript however, it's not possible to comprehensively detect all cases. Bugs and undefined behavior such as infinite loops may occur in those cases.
+Однако из-за гибкой и динамичной природы JavaScript невозможно всесторонне обнаружить все случаи. В таких случаях могут возникнуть ошибки и неопределенное поведение, например, бесконечные циклы.
-If your app doesn't work properly after compilation and you aren't seeing any ESLint errors, the compiler may be incorrectly compiling your code. To confirm this, try to make the issue go away by aggressively opting out any component or hook you think might be related via the [`"use no memo"` directive](#opt-out-of-the-compiler-for-a-component).
+Если ваше приложение не работает должным образом после компиляции, и вы не видите ошибок ESLint, компилятор может неправильно компилировать ваш код. Чтобы подтвердить это, попробуйте устранить проблему, агрессивно исключив любой компонент или хук, который, по вашему мнению, может быть связан, с помощью директивы [`"use no memo"`](#opt-out-of-the-compiler-for-a-component).
```js {2}
function SuspiciousComponent() {
- "use no memo"; // opts out this component from being compiled by React Compiler
+ "use no memo"; // исключает этот компонент из компиляции React Compiler
// ...
}
```
@@ -334,13 +334,13 @@ function SuspiciousComponent() {
#### `"use no memo"` {/*use-no-memo*/}
-`"use no memo"` is a _temporary_ escape hatch that lets you opt-out components and hooks from being compiled by the React Compiler. This directive is not meant to be long lived the same way as eg [`"use client"`](/reference/rsc/use-client) is.
+`"use no memo"` — это _временный_ обходной путь, который позволяет исключать компоненты и хуки из компиляции React Compiler. Эта директива не предназначена для долгосрочного использования, как, например, [`"use client"`](/reference/rsc/use-client).
-It is not recommended to reach for this directive unless it's strictly necessary. Once you opt-out a component or hook, it is opted-out forever until the directive is removed. This means that even if you fix the code, the compiler will still skip over compiling it unless you remove the directive.
+Не рекомендуется использовать эту директиву, если это не строго необходимо. Как только вы исключите компонент или хук, он будет исключен навсегда, пока директива не будет удалена. Это означает, что даже если вы исправите код, компилятор все равно пропустит его компиляцию, если вы не удалите директиву.
-When you make the error go away, confirm that removing the opt out directive makes the issue come back. Then share a bug report with us (you can try to reduce it to a small repro, or if it's open source code you can also just paste the entire source) using the [React Compiler Playground](https://playground.react.dev) so we can identify and help fix the issue.
+Когда вы устраните ошибку, подтвердите, что удаление директивы исключения возвращает проблему. Затем отправьте нам отчет об ошибке (вы можете попытаться свести его к минимальному воспроизводимому примеру, или, если это открытый исходный код, вы также можете просто вставить весь исходный код), используя [React Compiler Playground](https://playground.react.dev), чтобы мы могли выявить и помочь исправить проблему.
-### Other issues {/*other-issues*/}
+### Другие проблемы {/*other-issues*/}
-Please see https://github.com/reactwg/react-compiler/discussions/7.
+Пожалуйста, см. https://github.com/reactwg/react-compiler/discussions/7.