From 0945176f1393ef4a51601be0a1aad0c166929e61 Mon Sep 17 00:00:00 2001 From: Mikel Miras <48697824+mikelmiras@users.noreply.github.com> Date: Thu, 27 Apr 2023 15:05:47 +0200 Subject: [PATCH 01/14] Begin translation renderToReadableStream Begin renderToReadableStream translation to spanish --- .../server/renderToReadableStream.md | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/content/reference/react-dom/server/renderToReadableStream.md b/src/content/reference/react-dom/server/renderToReadableStream.md index 3f610d65a..10f2a765d 100644 --- a/src/content/reference/react-dom/server/renderToReadableStream.md +++ b/src/content/reference/react-dom/server/renderToReadableStream.md @@ -4,7 +4,7 @@ title: renderToReadableStream -`renderToReadableStream` renders a React tree to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) +`renderToReadableStream` renderiza un arbol de React a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) ```js const stream = await renderToReadableStream(reactNode, options?) @@ -22,11 +22,11 @@ This API depends on [Web Streams.](https://developer.mozilla.org/en-US/docs/Web/ --- -## Reference {/*reference*/} +## Referencias {/*reference*/} ### `renderToReadableStream(reactNode, options?)` {/*rendertoreadablestream*/} -Call `renderToReadableStream` to render your React tree as HTML into a [Node.js Stream.](https://nodejs.org/api/stream.html#writable-streams) +Llama a la función `renderToReadableStream` para renderizar tu árbol de React como HTML a [Stream de Node.js.](https://nodejs.org/api/stream.html#writable-streams) ```js import { renderToReadableStream } from 'react-dom/server'; @@ -41,24 +41,24 @@ async function handler(request) { } ``` -On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive. +Desde el cliente, llama a [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) para hacer interactivo el HTML generado en el servidor. -[See more examples below.](#usage) +[Consulta los ejemplos más abajo.](#usage) -#### Parameters {/*parameters*/} +#### Parámetros {/*parameters*/} -* `reactNode`: A React node you want to render to HTML. For example, a JSX element like ``. It is expected to represent the entire document, so the `App` component should render the `` tag. +* `reactNode`: Nodo de React que quieras renderizar a HTML. Por ejemplo, un elemento JSX como ``. Se presupone que representará el documento completo, por lo que el componente `App` debería renderizar la etiqueta ``. -* **optional** `options`: An object with streaming options. - * **optional** `bootstrapScriptContent`: If specified, this string will be placed in an inline ` + ``` -```js [[1, 1, "App"]] -export default function App() { - return ( - - - - - - My app - - - - - - ); -} -``` + En el cliente, tu script de arranque debería [hidratar el `document` entero con una llamada a `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document) -React will inject the [doctype](https://developer.mozilla.org/en-US/docs/Glossary/Doctype) and your bootstrap ` -``` - -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) - -```js [[1, 4, ""]] -import { hydrateRoot } from 'react-dom/client'; -import App from './App.js'; - -hydrateRoot(document, ); -``` - -This will attach event listeners to the server-generated HTML and make it interactive. - - - -#### Reading CSS and JS asset paths from the build output {/*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. - -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: - -```js {1,6} -export default function App({ assetMap }) { - return ( - - - My app - - - ... - - ); -} -``` - -On the server, render `` and pass your `assetMap` with the asset URLs: - -```js {1-5,8,9} -// You'd need to get this JSON from your build tooling, e.g. read it from the build output. -const assetMap = { - 'styles.css': '/styles.123456.css', - 'main.js': '/main.123456.js' -}; - -async function handler(request) { - const stream = await renderToReadableStream(, { - bootstrapScripts: [assetMap['/main.js']] - }); - return new Response(stream, { - headers: { 'content-type': 'text/html' }, - }); -} -``` - -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: - -```js {9-10} -// You'd need to get this JSON from your build tooling. -const assetMap = { - 'styles.css': '/styles.123456.css', - 'main.js': '/main.123456.js' -}; - -async function handler(request) { - const stream = await renderToReadableStream(, { - // Careful: It's safe to stringify() this because this data isn't user-generated. - bootstrapScriptContent: `window.assetMap = ${JSON.stringify(assetMap)};`, - bootstrapScripts: [assetMap['/main.js']], - }); - return new Response(stream, { - headers: { 'content-type': 'text/html' }, - }); -} -``` - -In the example above, the `bootstrapScriptContent` option adds an extra inline ` +## Uso {/*usage*/} + +### Renderizar árbol de React como HTML a Readable Web Stream {/*rendering-a-react-tree-as-html-to-a-readable-web-stream*/} + +Llama `renderToReadableStream` para renderizar tu árbol de React como HTML a [Readable Web Stream:](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) + +```js [[1, 4, ""], [2, 5, "['/main.js']"]] +import { renderToReadableStream } from 'react-dom/server'; + +async function handler(request) { + const stream = await renderToReadableStream(, { + bootstrapScripts: ['/main.js'] + }); + return new Response(stream, { + headers: { 'content-type': 'text/html' }, + }); +} +``` + +Junto al componente raíz, necesitas proporcionar una lista de rutas de ` ``` - En el cliente, tu script de arranque debería [hidratar el `document` entero con una llamada a `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document) +En el cliente, tu script de arranque debería [hidratar el `document` entero con una llamada a `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document) - ```js [[1, 4, ""]] - import { hydrateRoot } from 'react-dom/client'; - import App from './App.js'; +```js [[1, 4, ""]] +import { hydrateRoot } from 'react-dom/client'; +import App from './App.js'; - hydrateRoot(document, ); - ``` +hydrateRoot(document, ); +``` - Esto adjuntará detectores de eventos al HTML generado en el servidor, haciendo que este sea interactivo. +Esto adjuntará detectores de eventos al HTML generado en el servidor, haciendo que este sea interactivo. - + - #### Leer recursos CSS y JS mediante su ruta a través del output {/*reading-css-and-js-asset-paths-from-the-build-output*/} +#### Leer recursos CSS y JS mediante su ruta a través del output {/*reading-css-and-js-asset-paths-from-the-build-output*/} - Las URL finales de los recursos (como los archivos CSS y JS) suelen ser hasheadas después de la compilación. Por ejemplo, en lugar de `estilos.css` podrías tener `estilos.123456.css`. Hashear nombres de archivos estáticos garantiza que cada build distinta del mismo recurso tendrá un nombre de archivo diferente. Esto es útil porque te permite activar de forma segura el almacenamiento en caché a largo plazo para recursos estáticos: un archivo con un nombre característico nunca cambiaría su contenido. +Las URL finales de los recursos (como los archivos CSS y JS) suelen ser hasheadas después de la compilación. Por ejemplo, en lugar de `estilos.css` podrías tener `estilos.123456.css`. Hashear nombres de archivos estáticos garantiza que cada build distinta del mismo recurso tendrá un nombre de archivo diferente. Esto es útil porque te permite activar de forma segura el almacenamiento en caché a largo plazo para recursos estáticos: un archivo con un nombre característico nunca cambiaría su contenido. - Sin embargo, si no conoces las URLs de los recursos hasta después de tener la build, no te será posible ponerlas en el código fuente. Por ejemplo, *hardcod*eas `"/styles.css"` en JSX, esto no funcionaría, puesto que es una URL relativa. Para mantenerlas fuera del código fuente, tu componente raíz puede leer el nombre real de un archivo a través de un mapa pasado como propiedad: +Sin embargo, si no conoces las URLs de los recursos hasta después de tener la build, no te será posible ponerlas en el código fuente. Por ejemplo, *hardcod*eas `"/styles.css"` en JSX, esto no funcionaría, puesto que es una URL relativa. Para mantenerlas fuera del código fuente, tu componente raíz puede leer el nombre real de un archivo a través de un mapa pasado como propiedad: - ```js {1,6} - export default function App({ assetMap }) { - return ( - - - Mi app - - - ... - - ); - } - ``` - - En el servidor, renderiza `` y pasa tu `assetMap` con las URLs de los recursos: - - ```js {1-5,8,9} - // Necesitarás obtener este JSON a través de tus herramientas de compilación. Por ejemplo, leyéndolo desde la consola de compilación - const assetMap = { - 'estilos.css': '/estilos.123456.css', - 'main.js': '/main.123456.js' - }; +```js {1,6} +export default function App({ assetMap }) { + return ( + + + Mi app + + + ... + + ); +} +``` - async function handler(request) { - const stream = await renderToReadableStream(, { - bootstrapScripts: [assetMap['/main.js']] - }); - return new Response(stream, { - headers: { 'content-type': 'text/html' }, - }); - } - ``` +En el servidor, renderiza `` y pasa tu `assetMap` con las URLs de los recursos: - Dado que es el servidor quien está renderizando ``, necesitarás renderizarlo con `assetMap` en el cliente también para evitar errores de hidratación. Puedes serializar y pasar `assetMap` al cliente de esta forma: +```js {1-5,8,9} +// Necesitarás obtener este JSON a través de tus herramientas de compilación. Por ejemplo, leyéndolo desde laconsola de compilación +const assetMap = { + 'estilos.css': '/estilos.123456.css', + 'main.js': '/main.123456.js' +}; - ```js {9-10} - // Necesitarás obtener este JSON a través de tus herramientas de compilación. - const assetMap = { - 'estilos.css': '/estilos.123456.css', - 'main.js': '/main.123456.js' - }; +async function handler(request) { + const stream = await renderToReadableStream(, { + bootstrapScripts: [assetMap['/main.js']] + }); + return new Response(stream, { + headers: { 'content-type': 'text/html' }, + }); +} +``` - async function handler(request) { - const stream = await renderToReadableStream(, { - // Precaución: Es seguro usar stringify() aquí porque esta data no ha sido generada por el usuario. - bootstrapScriptContent: `window.assetMap = ${JSON.stringify(assetMap)};`, - bootstrapScripts: [assetMap['/main.js']], - }); - return new Response(stream, { - headers: { 'content-type': 'text/html' }, - }); - } - ``` +Dado que es el servidor quien está renderizando ``, necesitarás renderizarlo con `assetMap` en el cliente también para evitar errores de hidratación. Puedes serializar y pasar `assetMap` al cliente de esta forma: - En el ejemplo de arriba, la opción `bootstrapScriptContent` añade una etiqueta ` - ``` -En el cliente, tu script de arranque debería [hidratar el `document` entero con una llamada a `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document) +En el cliente, tu script inicial debería [hidratar el `document` entero con una llamada a `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document) ```js [[1, 4, ""]] import { hydrateRoot } from 'react-dom/client'; @@ -140,7 +139,7 @@ Esto adjuntará detectores de eventos al HTML generado en el servidor, haciendo #### Leer recursos CSS y JS mediante su ruta a través del output {/*reading-css-and-js-asset-paths-from-the-build-output*/} -Las URL finales de los recursos (como los archivos CSS y JS) suelen ser hasheadas después de la compilación. Por ejemplo, en lugar de `estilos.css` podrías tener `estilos.123456.css`. Hashear nombres de archivos estáticos garantiza que cada build distinta del mismo recurso tendrá un nombre de archivo diferente. Esto es útil porque te permite activar de forma segura el almacenamiento en caché a largo plazo para recursos estáticos: un archivo con un nombre característico nunca cambiaría su contenido. +Las URL finales de los recursos (como los archivos CSS y JS) suelen ser hasheadas después de la compilación. Por ejemplo, en lugar de `estilos.css` podrías tener `estilos.123456.css`. El hasheo de nombres de archivos estáticos garantiza que cada versión distinta del mismo recurso tendrá un nombre de archivo diferente. Esto es útil porque te permite activar de forma segura el almacenamiento en caché a largo plazo para recursos estáticos: un archivo con un nombre característico nunca cambiaría su contenido. Sin embargo, si no conoces las URLs de los recursos hasta después de tener el build, no te será posible ponerlas en el código fuente. Por ejemplo, si hardcodeas `"/styles.css"` en JSX, esto no funcionaría, puesto que es una URL relativa. Para mantenerlas fuera del código fuente, tu componente raíz puede leer el nombre real de un archivo a través de un mapa pasado como propiedad: