From 20aed67dc90ab79b64d07c1ba43623967805e8e0 Mon Sep 17 00:00:00 2001 From: Alexandra Pastouchova Date: Thu, 5 Jun 2025 06:23:57 +0100 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE=D0=B4:=20B?= =?UTF-8?q?uild=20a=20React=20App=20from=20scratch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../learn/build-a-react-app-from-scratch.md | 102 +++++++++--------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/src/content/learn/build-a-react-app-from-scratch.md b/src/content/learn/build-a-react-app-from-scratch.md index b5f29e9af..89e6c9b32 100644 --- a/src/content/learn/build-a-react-app-from-scratch.md +++ b/src/content/learn/build-a-react-app-from-scratch.md @@ -1,143 +1,143 @@ --- -title: Build a React app from Scratch +title: Создание приложения React с нуля --- -If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, you can build a React app from scratch. +Если ваше приложение имеет ограничения, с которыми плохо справляются существующие фреймворки, вы предпочитаете создать собственный фреймворк или просто хотите изучить основы React-приложений, вы можете собрать приложение React с нуля. -#### Consider using a framework {/*consider-using-a-framework*/} +#### Рассмотрите возможность использования фреймворка {/*consider-using-a-framework*/} -Starting from scratch is an easy way to get started using React, but a major tradeoff to be aware of is that going this route is often the same as building your own adhoc framework. As your requirements evolve, you may need to solve more framework-like problems that our recommended frameworks already have well developed and supported solutions for. +Начать с нуля — это простой способ познакомиться с React, но важно понимать, что такой подход зачастую сводится к созданию собственного, спонтанно сформированного фреймворка. По мере роста требований вам, скорее всего, придётся решать задачи, характерные для фреймворков, для которых в рекомендованных нами решениях уже есть хорошо проработанные и поддерживаемые решения. -For example, if in the future your app needs support for server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC), you will have to implement those on your own. Similarly, future React features that require integrating at the framework level will have to be implemented on your own if you want to use them. +Например, если в будущем вашему приложению потребуется поддержка серверного рендеринга (SSR), статической генерации (SSG) или React Server Components (RSC), вам придётся реализовать это самостоятельно. То же самое касается будущих возможностей React, которые требуют глубокой интеграции на уровне фреймворка и которые вам придётся реализовывать самостоятельно, если вы захотите их использовать. -Our recommended frameworks also help you build better performing apps. For example, reducing or eliminating waterfalls from network requests makes for a better user experience. This might not be a high priority when you are building a toy project, but if your app gains users you may want to improve its performance. +Рекомендованные нами фреймворки также помогают создавать более производительные приложения. Например, сокращение или устранение каскадов сетевых запросов улучшает пользовательский опыт. Это может быть не так важно на этапе создания небольшого проекта, но с ростом числа пользователей производительность может стать приоритетом. -Going this route also makes it more difficult to get support, since the way you develop routing, data-fetching, and other features will be unique to your situation. You should only choose this option if you are comfortable tackling these problems on your own, or if you’re confident that you will never need these features. +Кроме того, такой путь усложняет получение поддержки: ваша реализация маршрутизации, получения данных и других функций будет уникальной. Выбирайте этот путь только в том случае, если готовы самостоятельно решать все возникающие задачи или уверены, что вам никогда не понадобится соответствующий функционал. -For a list of recommended frameworks, check out [Creating a React App](/learn/creating-a-react-app). +Для списка рекомендуемых фреймворков смотрите [Создание React-приложения](/learn/creating-a-react-app). -## Step 1: Install a build tool {/*step-1-install-a-build-tool*/} +## Шаг 1: Установка инструмента сборки {/*step-1-install-a-build-tool*/} -The first step is to install a build tool like `vite`, `parcel`, or `rsbuild`. These build tools provide features to package and run source code, provide a development server for local development and a build command to deploy your app to a production server. +Первым шагом будет установка инструмента сборки, например, `vite`, `parcel`, или `rsbuild`. Эти инструменты позволяют упаковывать и запускать исходный код, предоставляют локальный сервер разработки и команду сборки для деплоя приложения на продакшн-сервер. ### Vite {/*vite*/} -[Vite](https://vite.dev/) is a build tool that aims to provide a faster and leaner development experience for modern web projects. +[Vite](https://vite.dev/) — это инструмент сборки, нацеленный на быструю и лёгкую разработку современных веб-приложений. {`npm create vite@latest my-app -- --template react`} -Vite is opinionated and comes with sensible defaults out of the box. Vite has a rich ecosystem of plugins to support fast refresh, JSX, Babel/SWC, and other common features. See Vite's [React plugin](https://vite.dev/plugins/#vitejs-plugin-react) or [React SWC plugin](https://vite.dev/plugins/#vitejs-plugin-react-swc) and [React SSR example project](https://vite.dev/guide/ssr.html#example-projects) to get started. +Vite следует определённой философии и поставляется с продуманными настройками по умолчанию. У него также есть богатая экосистема плагинов, поддерживающих fast refresh, JSX, Babel/SWC и других функций. Ознакомьтесь с [React-плагином для Vite](https://vite.dev/plugins/#vitejs-plugin-react) или [React SWC-плагином](https://vite.dev/plugins/#vitejs-plugin-react-swc), а также [примером проекта SSR на Vite](https://vite.dev/guide/ssr.html#example-projects), чтобы начать работу. -Vite is already being used as a build tool in one of our [recommended frameworks](/learn/creating-a-react-app): [React Router](https://reactrouter.com/start/framework/installation). +Vite уже используется как инструмент сборки в одном из [рекомендованных нами фреймворков](/learn/creating-a-react-app): [React Router](https://reactrouter.com/start/framework/installation). ### Parcel {/*parcel*/} -[Parcel](https://parceljs.org/) combines a great out-of-the-box development experience with a scalable architecture that can take your project from just getting started to massive production applications. +[Parcel](https://parceljs.org/) совмещает удобство начальной настройки с масштабируемой архитектурой, которая позволяет развивать проект от простого прототипа до крупного продакшн-приложения. {`npm install --save-dev parcel`} -Parcel supports fast refresh, JSX, TypeScript, Flow, and styling out of the box. See [Parcel's React recipe](https://parceljs.org/recipes/react/#getting-started) to get started. +Parcel поддерживает встроенную поддержку fast refresh, JSX, TypeScript, Flow и стилизацию. Ознакомьтесь с [Parcel's React рецептом](https://parceljs.org/recipes/react/#getting-started), чтобы начать. ### Rsbuild {/*rsbuild*/} -[Rsbuild](https://rsbuild.dev/) is an Rspack-powered build tool that provides a seamless development experience for React applications. It comes with carefully tuned defaults and performance optimizations ready to use. +[Rsbuild](https://rsbuild.dev/) — это инструмент сборки на базе Rspack, который предлагает безупречную систему для разработки React-приложений. Он включает в себя оптимизированные настройки и улучшения производительности. {`npx create-rsbuild --template react`} -Rsbuild includes built-in support for React features like fast refresh, JSX, TypeScript, and styling. See [Rsbuild's React guide](https://rsbuild.dev/guide/framework/react) to get started. +Rsbuild поддерживает встроенную поддержку fast refresh, JSX, TypeScript и стилизацию. Ознакомьтесь с [Rsbuild's React руководство](https://rsbuild.dev/guide/framework/react), чтобы начать. -#### Metro for React Native {/*react-native*/} +#### Metro для React Native {/*react-native*/} -If you're starting from scratch with React Native you'll need to use [Metro](https://metrobundler.dev/), the JavaScript bundler for React Native. Metro supports bundling for platforms like iOS and Android, but lacks many features when compared to the tools here. We recommend starting with Vite, Parcel, or Rsbuild unless your project requires React Native support. +Если вы создаёте приложение React Native с нуля, вам понадобится [Metro](https://metrobundler.dev/) — бандлер JavaScript-кода для React Native. Он поддерживает сборку для iOS и Android, но в нём отсутствуют многие функции, представленные в вышеуказанных инструментах. Если только вы не работаете с React Native, мы рекомендуем использовать Vite, Parcel или Rsbuild. -## Step 2: Build Common Application Patterns {/*step-2-build-common-application-patterns*/} +## Шаг 2: Реализация распространённых паттернов приложения {/*step-2-build-common-application-patterns*/} -The build tools listed above start off with a client-only, single-page app (SPA), but don't include any further solutions for common functionality like routing, data fetching, or styling. +Инструменты сборки, упомянутые выше, позволяют начать с клиентского одностраничного приложения (SPA), но не предоставляют решения для таких задач, как маршрутизация, получение данных или стилизация. -The React ecosystem includes many tools for these problems. We've listed a few that are widely used as a starting point, but feel free to choose other tools if those work better for you. +Экосистема React предлагает множество решений для этих задач. Ниже приведены наиболее популярные из них — вы можете выбрать их или использовать альтернативы, если они вам ближе. -### Routing {/*routing*/} +### Маршрутизация {/*routing*/} -Routing determines what content or pages to display when a user visits a particular URL. You need to set up a router to map URLs to different parts of your app. You'll also need to handle nested routes, route parameters, and query parameters. Routers can be configured within your code, or defined based on your component folder and file structures. +Маршрутизация определяет, какой контент или страницу показывать пользователю при переходе по определённому URL. Необходимо настроить маршрутизатор, чтобы сопоставлять URL-адреса с разными частями приложения. Также нужно обрабатывать вложенные маршруты, параметры маршрута и параметры запроса. Маршруты можно описывать в коде или определять по структуре файлов и папок. -Routers are a core part of modern applications, and are usually integrated with data fetching (including prefetching data for a whole page for faster loading), code splitting (to minimize client bundle sizes), and page rendering approaches (to decide how each page gets generated). +Современные маршрутизаторы обычно включают поддержку получения данных (в том числе префетчинга для ускоренной загрузки страниц), разделения кода (для уменьшения размера клиентского бандла) и способов рендеринга страниц (чтобы определить, как будет формироваться каждая страница). -We suggest using: +Рекомендуем использовать: - [React Router](https://reactrouter.com/start/data/custom) - [Tanstack Router](https://tanstack.com/router/latest) -### Data Fetching {/*data-fetching*/} +### Получение данных {/*data-fetching*/} -Fetching data from a server or other data source is a key part of most applications. Doing this properly requires handling loading states, error states, and caching the fetched data, which can be complex. +Получение данных с сервера или другого источника — ключевая часть большинства приложений. Чтобы всё работало правильно, нужно учитывать состояние загрузки, ошибки и кэширование данных — всё это может быть сложно реализовать вручную. -Purpose-built data fetching libraries do the hard work of fetching and caching the data for you, letting you focus on what data your app needs and how to display it. These libraries are typically used directly in your components, but can also be integrated into routing loaders for faster pre-fetching and better performance, and in server rendering as well. +Специализированные библиотеки для получения данных берут эти задачи на себя. Они позволяют сосредоточиться на том, какие данные нужны приложению и как их отображать.Такие библиотеки можно использовать прямо внутри компонентов, а также интегрировать в загрузчики маршрутов для ускоренного префетчинга и повышения производительности, включая использование при серверном рендеринге. -Note that fetching data directly in components can lead to slower loading times due to network request waterfalls, so we recommend prefetching data in router loaders or on the server as much as possible! This allows a page's data to be fetched all at once as the page is being displayed. +Важно: если загружать данные прямо в компонентах, это может привести к каскадной задержке (waterfall). Лучше делать префетчинг в загрузчиках маршрутов или на сервере — это позволит загрузить все данные до или во время рендера страницы. -If you're fetching data from most backends or REST-style APIs, we suggest using: +Если вы получаете данные с большинства бэкендов или REST‑API, мы рекомендуем использовать: - [React Query](https://react-query.tanstack.com/) - [SWR](https://swr.vercel.app/) - [RTK Query](https://redux-toolkit.js.org/rtk-query/overview) -If you're fetching data from a GraphQL API, we suggest using: +Если вы работаете с GraphQL‑API, мы рекомендуем использовать: - [Apollo](https://www.apollographql.com/docs/react) - [Relay](https://relay.dev/) -### Code-splitting {/*code-splitting*/} +### Разделение кода {/*code-splitting*/} -Code-splitting is the process of breaking your app into smaller bundles that can be loaded on demand. An app's code size increases with every new feature and additional dependency. Apps can become slow to load because all of the code for the entire app needs to be sent before it can be used. Caching, reducing features/dependencies, and moving some code to run on the server can help mitigate slow loading but are incomplete solutions that can sacrifice functionality if overused. +Разделение кода — это процесс разбиения приложения на более мелкие бандлеры, которые подгружаются по мере необходимости. По мере добавления новых функций и зависимостей размер клиентского кода увеличивается. Это может привести к тому, что приложение начнёт загружаться медленно, поскольку весь код нужно будет передать в браузер до начала работы. Снизить задержки помогают такие подходы, как кэширование, отказ от неиспользуемых функций и зависимостей, а также перенос части кода на сервер. Однако эти методы не являются полноценным решением и при чрезмерном использовании могут начать ограничивать функциональность приложения. -Similarly, if you rely on the apps using your framework to split the code, you might encounter situations where loading becomes slower than if no code splitting were happening at all. For example, [lazily loading](/reference/react/lazy) a chart delays sending the code needed to render the chart, splitting the chart code from the rest of the app. [Parcel supports code splitting with React.lazy](https://parceljs.org/recipes/react/#code-splitting). However, if the chart loads its data *after* it has been initially rendered you are now waiting twice. This is a waterfall: rather than fetching the data for the chart and sending the code to render it simultaneously, you must wait for each step to complete one after the other. +Если вы полагаетесь на то, что само приложение будет делить код, вы можете столкнуться с ситуацией, когда загрузка становится даже медленнее, чем без разделения. Например, [lazily loading](/reference/react/lazy) — если вы отложенно подгружаете компонент диаграммы, сначала загружается сам код диаграммы (отдельно от остального кода приложения), а затем — данные для её отображения. [Parcel поддерживает разделение кода с помощью React.lazy](https://parceljs.org/recipes/react/#code-splitting). Однако если данные для диаграммы загружаются уже после того, как она была отрендерена, пользователю придётся ждать дважды. Это и называется эффектом "waterfall": вместо одновременной загрузки данных и кода, вы ждёте выполнения одного шага за другим. -Splitting code by route, when integrated with bundling and data fetching, can reduce the initial load time of your app and the time it takes for the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)). +Разделение кода по маршрутам — особенно в сочетании с бандлингом и загрузкой данных — может существенно сократить начальное время загрузки приложения и ускорить отображение основного контента — ([Largest Contentful Paint](https://web.dev/articles/lcp)). -For code-splitting instructions, see your build tool docs: -- [Vite build optimizations](https://vite.dev/guide/features.html#build-optimizations) -- [Parcel code splitting](https://parceljs.org/features/code-splitting/) -- [Rsbuild code splitting](https://rsbuild.dev/guide/optimization/code-splitting) +Для инструкций по разделению кода смотрите документацию: +- [Оптимизация сборки в Vite](https://vite.dev/guide/features.html#build-optimizations) +- [Разделение кода в Parcel](https://parceljs.org/features/code-splitting/) +- [Разделение кода в Parcel](https://rsbuild.dev/guide/optimization/code-splitting) -### Improving Application Performance {/*improving-application-performance*/} +### Повышение производительности приложения {/*improving-application-performance*/} -Since the build tool you select only support single page apps (SPAs) you'll need to implement other [rendering patterns](https://www.patterns.dev/vanilla/rendering-patterns) like server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC). Even if you don't need these features at first, in the future there may be some routes that would benefit SSR, SSG or RSC. +Так как выбранные вами инструменты сборки по умолчанию поддерживают только одностраничные приложения (SPA), для повышения производительности может потребоваться реализовать другие [подходы к рендерингу](https://www.patterns.dev/vanilla/rendering-patterns), такие как серверный рендеринг (SSR), статическая генерация сайта (SSG) и/или React Server Components (RSC). Даже если на начальном этапе такие возможности вам не нужны, в будущем может появиться необходимость использовать SSR, SSG или RSC для отдельных маршрутов приложения. -* **Single-page apps (SPA)** load a single HTML page and dynamically updates the page as the user interacts with the app. SPAs are easier to get started with, but they can have slower initial load times. SPAs are the default architecture for most build tools. +* **Одностраничные приложения (SPA)** — загружают один HTML-файл и динамически обновляют содержимое по мере взаимодействия пользователя с приложением. Такой подход упрощает старт разработки, но может приводить к более медленной первоначальной загрузке. Для большинства инструментов сборки архитектура SPA является вариантом по умолчанию. -* **Streaming Server-side rendering (SSR)** renders a page on the server and sends the fully rendered page to the client. SSR can improve performance, but it can be more complex to set up and maintain than a single-page app. With the addition of streaming, SSR can be very complex to set up and maintain. See [Vite's SSR guide]( https://vite.dev/guide/ssr). +* **Серверный рендеринг (SSR) с потоковой передачей** — выполняет рендеринг страницы на сервере и отправляет клиенту уже готовый HTML. Это может существенно улучшить производительность, но требует более сложной настройки и сопровождения по сравнению с SPA. А добавление потоковой передачи (streaming) делает SSR ещё более сложным в реализации. Смотрите: [руководство по SSR для Vite]( https://vite.dev/guide/ssr). -* **Static site generation (SSG)** generates static HTML files for your app at build time. SSG can improve performance, but it can be more complex to set up and maintain than server-side rendering. See [Vite's SSG guide](https://vite.dev/guide/ssr.html#pre-rendering-ssg). +* **Статическая генерация сайта (SSG)** — создаёт статические HTML-файлы для вашего приложения во время сборки. Это улучшает производительность, но настройка и поддержка могут оказаться даже сложнее, чем при использовании SSR. Смотрите: [руководство по SSG для Vite](https://vite.dev/guide/ssr.html#pre-rendering-ssg). -* **React Server Components (RSC)** lets you mix build-time, server-only, and interactive components in a single React tree. RSC can improve performance, but it currently requires deep expertise to set up and maintain. See [Parcel's RSC examples](https://github.com/parcel-bundler/rsc-examples). +* **React Server Components (RSC)** — RSC позволяют объединять компоненты, рендерящиеся во время сборки, только на сервере и интерактивные компоненты в одном дереве React. Это может серьёзно повысить производительность приложения, но на текущем этапе требует глубокой технической подготовки и опыта для настройки и сопровождения. Смотрите: [примеры RSC для Parcel](https://github.com/parcel-bundler/rsc-examples). -Your rendering strategies need to integrate with your router so apps built with your framework can choose the rendering strategy on a per-route level. This will enable different rendering strategies without having to rewrite your whole app. For example, the landing page for your app might benefit from being statically generated (SSG), while a page with a content feed might perform best with server-side rendering. +Ваша стратегия рендеринга должна быть интегрирована с маршрутизатором, чтобы приложения, построенные на вашем фреймворке, могли выбирать подходящий способ рендеринга для каждого маршрута. Это позволит применять разные стратегии без необходимости переписывать всё приложение. Например, главная страница может быть сгенерирована статически (SSG), а лента новостей — рендериться на сервере (SSR) для большей динамичности. -Using the right rendering strategy for the right routes can decrease the time it takes for the first byte of content to be loaded ([Time to First Byte](https://web.dev/articles/ttfb)), the first piece of content to render ([First Contentful Paint](https://web.dev/articles/fcp)), and the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)). +Правильно подобранная стратегия рендеринга для каждого маршрута помогает сократить: ([Time to First Byte](https://web.dev/articles/ttfb))— время до получения первого байта контента, ([First Contentful Paint](https://web.dev/articles/fcp))— время до отображения первого видимого контента, ([Largest Contentful Paint](https://web.dev/articles/lcp)) — время до отображения основного содержимого страницы. -### And more... {/*and-more*/} +### И многое другое… {/*and-more*/} -These are just a few examples of the features a new app will need to consider when building from scratch. Many limitations you'll hit can be difficult to solve as each problem is interconnected with the others and can require deep expertise in problem areas you may not be familiar with. +Это лишь часть аспектов, которые стоит учитывать при создании приложения с нуля. Часто задачи тесно связаны друг с другом, и решение одной может потребовать глубокого понимания остальных. -If you don't want to solve these problems on your own, you can [get started with a framework](/learn/creating-a-react-app) that provides these features out of the box. +Если вы не хотите решать всё самостоятельно, начните с фреймворка, в который всё это уже встроено. \ No newline at end of file