diff --git a/src/content/reference/react-dom/static/prerenderToNodeStream.md b/src/content/reference/react-dom/static/prerenderToNodeStream.md index fb8073ef07..36b5e0fcc5 100644 --- a/src/content/reference/react-dom/static/prerenderToNodeStream.md +++ b/src/content/reference/react-dom/static/prerenderToNodeStream.md @@ -1,10 +1,9 @@ --- title: prerenderToNodeStream --- - -`prerenderToNodeStream` renders a React tree to a static HTML string using a [Node.js Stream.](https://nodejs.org/api/stream.html). +`prerenderToNodeStream` рендерит дерево React в статический HTML-строку с использованием [Node.js Stream.](https://nodejs.org/api/stream.html). ```js const {prelude} = await prerenderToNodeStream(reactNode, options?) @@ -16,22 +15,22 @@ const {prelude} = await prerenderToNodeStream(reactNode, options?) -This API is specific to Node.js. Environments with [Web Streams,](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) like Deno and modern edge runtimes, should use [`prerender`](/reference/react-dom/static/prerender) instead. +Этот API специфичен для Node.js. Среды с [Web Streams,](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) такими как Deno и современные серверные среды выполнения, должны использовать [`prerender`](/reference/react-dom/static/prerender) вместо этого. --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `prerenderToNodeStream(reactNode, options?)` {/*prerender*/} -Call `prerenderToNodeStream` to render your app to static HTML. +Вызовите `prerenderToNodeStream` для рендеринга вашего приложения в статический HTML. ```js import { prerenderToNodeStream } from 'react-dom/static'; -// The route handler syntax depends on your backend framework +// Синтаксис обработчика маршрута зависит от вашего серверного фреймворка app.use('/', async (request, response) => { const { prelude } = await prerenderToNodeStream(, { bootstrapScripts: ['/main.js'], @@ -42,55 +41,55 @@ app.use('/', async (request, response) => { }); ``` -On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive. +На клиенте вызовите [`hydrateRoot`](/reference/react-dom/client/hydrateRoot), чтобы сделать сгенерированный сервером HTML интерактивным. -[See more examples below.](#usage) +[См. больше примеров ниже.](#usage) -#### Parameters {/*parameters*/} +#### Параметры {/*parameters*/} -* `reactNode`: A React node you want to render to HTML. For example, a JSX node like ``. It is expected to represent the entire document, so the App component should render the `` tag. +* `reactNode`: Узел React, который вы хотите отрендерить в HTML. Например, JSX-узел вроде ``. Ожидается, что он будет представлять весь документ, поэтому компонент App должен рендерить тег ``. -* **optional** `options`: An object with static generation options. - * **optional** `bootstrapScriptContent`: If specified, this string will be placed in an inline ` ``` -On the client, your bootstrap script should [hydrate the entire `document` with a call to `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document) +На клиенте ваш скрипт инициализации должен [гидрировать весь `document` вызовом `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document) ```js [[1, 4, ""]] import { hydrateRoot } from 'react-dom/client'; @@ -142,15 +141,15 @@ import App from './App.js'; hydrateRoot(document, ); ``` -This will attach event listeners to the static server-generated HTML and make it interactive. +Это прикрепит обработчики событий к статическому HTML, сгенерированному сервером, и сделает его интерактивным. -#### Reading CSS and JS asset paths from the build output {/*reading-css-and-js-asset-paths-from-the-build-output*/} +#### Чтение путей к CSS и JS файлам из вывода сборки {/*reading-css-and-js-asset-paths-from-the-build-output*/} -The final asset URLs (like JavaScript and CSS files) are often hashed after the build. For example, instead of `styles.css` you might end up with `styles.123456.css`. Hashing static asset filenames guarantees that every distinct build of the same asset will have a different filename. This is useful because it lets you safely enable long-term caching for static assets: a file with a certain name would never change content. +Окончательные URL-адреса ресурсов (таких как файлы JavaScript и CSS) часто хешируются после сборки. Например, вместо `styles.css` вы можете получить `styles.123456.css`. Хеширование имён файлов статических ресурсов гарантирует, что каждая отдельная сборка одного и того же ресурса будет иметь другое имя файла. Это полезно, потому что позволяет безопасно включить долгосрочное кеширование для статических ресурсов: файл с определённым именем никогда не изменит своего содержимого. -However, if you don't know the asset URLs until after the build, there's no way for you to put them in the source code. For example, hardcoding `"/styles.css"` into JSX like earlier wouldn't work. To keep them out of your source code, your root component can read the real filenames from a map passed as a prop: +Однако, если вы не знаете URL-адреса ресурсов до завершения сборки, вы не сможете указать их в исходном коде. Например, жёсткое кодирование `"/styles.css"` в JSX, как было показано ранее, не сработает. Чтобы исключить их из вашего исходного кода, ваш корневой компонент может считывать реальные имена файлов из карты, передаваемой в качестве пропса: ```js {1,6} export default function App({ assetMap }) { @@ -166,10 +165,10 @@ export default function App({ assetMap }) { } ``` -On the server, render `` and pass your `assetMap` with the asset URLs: +На сервере рендерите `` и передавайте вашу `assetMap` с URL-адресами ресурсов: ```js {1-5,8,9} -// You'd need to get this JSON from your build tooling, e.g. read it from the build output. +// Вам нужно будет получить этот JSON из ваших инструментов сборки, например, прочитать его из вывода сборки. const assetMap = { 'styles.css': '/styles.123456.css', 'main.js': '/main.123456.js' @@ -185,10 +184,10 @@ app.use('/', async (request, response) => { }); ``` -Since your server is now rendering ``, you need to render it with `assetMap` on the client too to avoid hydration errors. You can serialize and pass `assetMap` to the client like this: +Поскольку ваш сервер теперь рендерит ``, вам также нужно будет рендерить его с `assetMap` на клиенте, чтобы избежать ошибок гидратации. Вы можете сериализовать и передать `assetMap` клиенту следующим образом: ```js {9-10} -// You'd need to get this JSON from your build tooling. +// Вам нужно будет получить этот JSON из ваших инструментов сборки. const assetMap = { 'styles.css': '/styles.123456.css', 'main.js': '/main.123456.js' @@ -196,7 +195,7 @@ const assetMap = { app.use('/', async (request, response) => { const { prelude } = await prerenderToNodeStream(, { - // Careful: It's safe to stringify() this because this data isn't user-generated. + // Осторожно: безопасно использовать stringify() это, потому что эти данные не генерируются пользователем. bootstrapScriptContent: `window.assetMap = ${JSON.stringify(assetMap)};`, bootstrapScripts: [assetMap['/main.js']], }); @@ -206,7 +205,7 @@ app.use('/', async (request, response) => { }); ``` -In the example above, the `bootstrapScriptContent` option adds an extra inline `