diff --git a/src/content/docs/en/guides/upgrade-to/v5.mdx b/src/content/docs/en/guides/upgrade-to/v5.mdx index e807eaf133de5..f66c46dba673d 100644 --- a/src/content/docs/en/guides/upgrade-to/v5.mdx +++ b/src/content/docs/en/guides/upgrade-to/v5.mdx @@ -1112,7 +1112,7 @@ function useRoute(route: IntegrationRouteData) { } ``` -See the [API reference for `IntegrationRouteData`](/en/reference/integrations-reference/#integrationroutedata-type-reference). +See the API reference for `IntegrationRouteData`. ### Changed: `distURL` is now an array (Integrations API) @@ -1139,7 +1139,7 @@ if (route.distURL) { } ``` -See the [API reference for `IntegrationRouteData`](/en/reference/integrations-reference/#integrationroutedata-type-reference). +See the [API reference for `IntegrationRouteData`. ### Changed: Arguments passed to `app.render()` (Adapter API) diff --git a/src/content/docs/en/guides/upgrade-to/v6.mdx b/src/content/docs/en/guides/upgrade-to/v6.mdx index 983472171468f..d16c28fc268e0 100644 --- a/src/content/docs/en/guides/upgrade-to/v6.mdx +++ b/src/content/docs/en/guides/upgrade-to/v6.mdx @@ -180,6 +180,71 @@ You may also wish to consider using glob packages from NPM, such as [`fast-glob` Learn more about [importing files with `import.meta.glob`](/en/guides/imports/#importmetaglob). +### Removed: `routes` on `astro:build:done` hook (Integration API) + + + +In Astro 5.0, accessing `routes` on the `astro:build:done` hook was deprecated. + +Astro 6.0 removes the `routes` array passed to this hook entirely. Instead, the `astro:routes:resolved` hook should be used. + +#### What should I do? + +Remove any instance of `routes` passed to `astro:build:done` and replace it with the new `astro:routes:resolved` hook. Access `distURL` on the newly exposed `assets` map: + +```js title="my-integration.mjs" ins={2,6-8,11,13-18} del={10} +const integration = () => { + let routes + return { + name: 'my-integration', + hooks: { + 'astro:routes:resolved': (params) => { + routes = params.routes + }, + 'astro:build:done': ({ + routes + assets + }) => { + for (const route of routes) { + const distURL = assets.get(route.pattern) + if (distURL) { + Object.assign(route, { distURL }) + } + } + console.log(routes) + } + } + } +} +``` + +Learn more about [the Integration API `astro:routes:resolved` hook](/en/reference/integrations-reference/#astroroutesresolved) for building integrations. + +### Removed: `entryPoints` on `astro:build:ssr` hook (Integration API) + + + +In Astro 5.0, [`functionPerRoute` was deprecated](/en/guides/upgrade-to/v5/#deprecated-functionperroute-adapter-api). That meant that `entryPoints` on the `astro:build:ssr` hook was always empty. + +Astro 6.0 removes the `entryPoints` map passed to this hook entirely. + +#### What should I do? + +Remove any instance of `entryPoints` passed to `astro:build:ssr`: + +```js title="my-integration.mjs" del={6} +const integration = () => { + return { + name: 'my-integration', + hooks: { + 'astro:build:ssr': (params) => { + someLogic(params.entryPoints) + }, + } + } +} +``` + ## Changed Defaults Some default behavior has changed in Astro v5.0 and your project code may need updating to account for these changes. diff --git a/src/content/docs/en/reference/adapter-reference.mdx b/src/content/docs/en/reference/adapter-reference.mdx index de3542df0e71f..6e8d70220ecb6 100644 --- a/src/content/docs/en/reference/adapter-reference.mdx +++ b/src/content/docs/en/reference/adapter-reference.mdx @@ -322,7 +322,7 @@ If not provided, Astro will fallback to its default behavior for fetching error **Default:** `app.match(request)`

-Provide a value for [`integrationRouteData`](/en/reference/integrations-reference/#integrationroutedata-type-reference) if you already know the route to render. Doing so will bypass the internal call to [`app.match`](#appmatch) to determine the route to render. +Provide a value for `integrationRouteData` if you already know the route to render. Doing so will bypass the internal call to [`app.match`](#appmatch) to determine the route to render. ```js "routeData" const routeData = app.match(request); diff --git a/src/content/docs/en/reference/integrations-reference.mdx b/src/content/docs/en/reference/integrations-reference.mdx index b24c204fa85ea..effb14d6da7c6 100644 --- a/src/content/docs/en/reference/integrations-reference.mdx +++ b/src/content/docs/en/reference/integrations-reference.mdx @@ -79,7 +79,6 @@ interface AstroIntegration { }) => void | Promise; 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest; - entryPoints: Map; middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger; }) => void | Promise; @@ -1036,13 +1035,11 @@ export default { **When:** After a production SSR build has completed. **Why:** To access the SSR manifest and map of the emitted entry points. This is useful when creating custom SSR builds in plugins or integrations. -- `entryPoints` maps a page route to the physical file emitted after the build; - `middlewareEntryPoint` is the file system path of the middleware file; ```js 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest; - entryPoints: Map; middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger; }) => void | Promise; @@ -1071,29 +1068,6 @@ export default { } ``` -#### `entryPoints` option - -

- -**Type:** Map\<IntegrationRouteData, URL\>
- -

- -A `Map` of the emitted entry points with the `IntegrationRouteData` as key and the physical file URL as value. - -```js -export default { - name: 'my-integration', - hooks: { - 'astro:build:ssr': ({ entryPoints }) => { - entryPoints.forEach((url) => { - console.log(url.href); - }); - }, - }, -} -``` - #### `middlewareEntryPoint` option

@@ -1173,8 +1147,6 @@ export default { 'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL; - /** @deprecated Use the `assets` map and the new `astro:routes:resolved` hook */ - routes: IntegrationRouteData[]; assets: Map; logger: AstroIntegrationLogger; }) => void | Promise; @@ -1207,24 +1179,6 @@ export default function myIntegration() { } ``` -#### `routes` option - -:::caution -This property is deprecated since v5.0. Check the [migration guide](/en/guides/upgrade-to/v5/#deprecated-routes-on-astrobuilddone-hook-integration-api). -::: - -

- -**Type:** [`IntegrationRouteData[]`](#integrationroutedata-type-reference) -

- -A list of all generated routes alongside their associated metadata. - -You can reference the full `IntegrationRouteData` type below, but the most common properties are: - -- `component` - the input file path relative to the project root -- `pathname` - the output file URL (undefined for routes using `[dynamic]` and `[...spread]` params) - #### `assets` option

@@ -1496,146 +1450,6 @@ Allows you to access the route to redirect to. This can be a string or an object Determines if a route comes from Astro core (`internal`), an integration (`external`) or the user's project (`project`). -### `IntegrationRouteData` type reference - -:::caution -This type is deprecated since v5.0. Use [`IntegrationResolvedRoute`](#integrationresolvedroute-type-reference) instead. -::: - -A smaller version of the `RouteData` that is used in the integrations. - -```ts -interface IntegrationRouteData { - type: RouteType; - component: string; - pathname?: string; - pattern: RegExp; - params: string[]; - segments: { content: string; dynamic: boolean; spread: boolean; }[][]; - generate: (data?: any) => string; - prerender: boolean; - distURL?: URL[]; - redirect?: RedirectConfig; - redirectRoute?: IntegrationRouteData; -} -``` - -#### `type` - -

- -**Type:** `RouteType` -

- -Allows you to identify the type of the route. The value can be: -- `page`: a route that lives in the file system, usually an Astro component -- `endpoint`: a route that lives in the file system, usually a JS file that exposes endpoints methods -- `redirect`: a route that points to another route that lives in the file system -- `fallback`: a route that doesn't exist in the file system and needs to be handled with other means, usually middleware - -#### `component` - -

- -**Type:** `string` -

- -Allows you to access the source component URL pathname. - -#### `pathname` - -

- -**Type:** `string | undefined` -

- -For regular routes, the value will be the URL pathname where this route will be served. When the project uses [dynamic routes](/en/guides/routing/#dynamic-routes) (ie. `[dynamic]` or `[...spread]`), the pathname will be undefined. - -#### `pattern` - -

- -**Type:** `RegExp` -

- -Allows you to access a regex used for matching an input URL against a requested route. - -For example, given a `[fruit]/about.astro` path, the regex will be `/^\/([^/]+?)\/about\/?$/`. Using `pattern.test("banana/about")` will return `true`. - -#### `params` - -

- -**Type:** `string[]` -

- -Allows you to access the route `params`. For example, when a project uses the following [dynamic routes](/en/guides/routing/#dynamic-routes) `/pages/[lang]/[...slug].astro`, the value will be `['lang', '...slug']`. - -#### `segments` - -

- -**Type:** `{ content: string; dynamic: boolean; spread: boolean; }[][]` -

- -Allows you to access the route [`params`](#params-1) with additional metadata. Each object contains the following properties: -* `content`: the `param`, -* `dynamic`: whether the route is dynamic or not, -* `spread`: whether the dynamic route uses the spread syntax or not. - -For example, the following route `/pages/[lang]/index.astro` will output the segments `[[ { content: 'lang', dynamic: true, spread: false } ]]`. - -#### `generate()` - -

- -**Type:** `(data?: any) => string` -

- -A function that provides the optional parameters of the route, interpolates them with the route pattern, and returns the path name of the route. - -For example, with a route such as `/blog/[...id].astro`, the `generate` function could return: - -```js -console.log(generate({ id: 'presentation' })) // will log `/blog/presentation` -``` - -#### `prerender` - -

- -**Type:** `boolean` -

- -Determines whether the route is prerendered or not. - -#### `distURL` - -

- -**Type:** `URL[] | undefined` -

- -The paths of the physical files emitted by this route. When a route **isn't** prerendered, the value is either `undefined` or an empty array. - -#### `redirect` - -

- -**Type:** RedirectConfig | undefined -

- -Allows you to access the route to redirect to. This can be a string or an object containing information about the status code and its destination. - -#### `redirectRoute` - -

- -**Type:** `IntegrationRouteData | undefined` -

- -When the value of `RouteData.type` is `redirect`, the value will contains the `IntegrationRouteData` of the route to redirect to. Otherwise, the value will be undefined. - ## Allow installation with `astro add` [The `astro add` command](/en/reference/cli-reference/#astro-add) allows users to easily add integrations and adapters to their project. If you want _your_ integration to be installable with this tool, **add `astro-integration` to the `keywords` field in your `package.json`**: diff --git a/src/content/docs/es/guides/internationalization.mdx b/src/content/docs/es/guides/internationalization.mdx index 7217fa1ddce44..8e39333bc74a3 100644 --- a/src/content/docs/es/guides/internationalization.mdx +++ b/src/content/docs/es/guides/internationalization.mdx @@ -339,7 +339,6 @@ Esta característica tiene algunas restricciones: - La opción `site` es obligatoria. - La opción `output` debe estar configurada en `"server"`. - No puede haber páginas prerenderizadas individuales. -- La característica del adaptador [`functionPerRoute`](/es/reference/adapter-reference/#functionperroute) no es admitida. Astro depende de los siguientes encabezados para admitir la función: - [`X-Forwarded-Host`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Host) y [`Host`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host). Astro usará el primero, y si no está presente, intentará el segundo. - [`X-Forwarded-Proto`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto) y [`URL#protocol`](https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol) de la solicitud del servidor. diff --git a/src/content/docs/es/reference/adapter-reference.mdx b/src/content/docs/es/reference/adapter-reference.mdx index 2e41cf3cdcac1..ab07827f917d1 100644 --- a/src/content/docs/es/reference/adapter-reference.mdx +++ b/src/content/docs/es/reference/adapter-reference.mdx @@ -57,10 +57,6 @@ export interface AstroAdapterFeatures { * Crea una función edge que se comunicará con el middleware de Astro */ edgeMiddleware: boolean; - /** - * Solo SSR. Cada ruta se convierte en su propia función/archivo - */ - functionPerRoute: boolean; } export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; @@ -338,89 +334,6 @@ y un error si el servicio utilizado para activos no es compatible con el adaptad Un conjunto de características que cambian la salida de los archivos emitidos. Cuando un adaptador elige habilitar estas características, recibirá información adicional dentro de hooks específicos. -### `functionPerRoute` - -Esta es una característica que se habilita al usar solo SSR. Por defecto, Astro emite un único archivo `entry.mjs`, que se encarga de emitir la página renderizada en cada solicitud. - -Cuando `functionPerRoute` está en `true`, Astro en su lugar creará un archivo separado para cada ruta definida en el proyecto. - -Cada archivo emitido solo renderizará una página. Las páginas se emitirán dentro de un directorio `dist/pages/`, y los archivos emitidos mantendrán las mismas rutas de archivo del directorio `src/pages/`. - -Los archivos dentro del directorio `pages/` de la compilación reflejarán la estructura de directorios de los archivos de página en `src/pages/`, por ejemplo: - - -- dist/ - - pages/ - - blog/ - - entry.\_slug\_.astro.mjs - - entry.about.astro.mjs - - entry.index.astro.mjs - - -Habilita la característica pasando `true` al adaptador. - -```js title="my-adapter.mjs" ins={9-11} -export default function createIntegration() { - return { - name: '@matthewp/my-adapter', - hooks: { - 'astro:config:done': ({ setAdapter }) => { - setAdapter({ - name: '@matthewp/my-adapter', - serverEntrypoint: '@matthewp/my-adapter/server.js', - adapterFeatures: { - functionPerRoute: true - } - }); - }, - }, - }; -} -``` - -Luego, utiliza el hook [`astro:build:ssr`](/es/reference/integrations-reference/#astrobuildssr), que te proporcionará un objeto `entryPoints` que mapea una ruta de página al archivo físico emitido después de la compilación. - -```js title="my-adapter.mjs" ins={15-19} -export default function createIntegration() { - return { - name: '@matthewp/my-adapter', - hooks: { - 'astro:config:done': ({ setAdapter }) => { - setAdapter({ - name: '@matthewp/my-adapter', - serverEntrypoint: '@matthewp/my-adapter/server.js', - adapterFeatures: { - functionPerRoute: true - } - }); - }, - - 'astro:build:ssr': ({ entryPoints }) => { - for (const [route, entryFile] of entryPoints) { - // haz algo con route y entryFile - } - } - }, - }; -} -``` - -:::caution -`entryFile` es de tipo `URL` y representa la ruta física del archivo en el sistema de archivos. Esto significa que las rutas cambian según el sistema operativo en el que se ejecute el código. -::: - -#### Entornos serverless - -Establecer `functionPerRoute: true` en un entorno serverless crea un archivo JavaScript (controlador) para cada ruta. El nombre de un controlador puede variar según la plataforma de alojamiento que estés utilizando: lambda, función, página, etc. - -Cada una de estas rutas está sujeta a un [arranque en frío](https://azure.microsoft.com/en-us/blog/understanding-serverless-cold-start/) cuando se ejecuta el controlador, lo que puede causar cierto retraso. Este retraso está influenciado por diferentes factores. - -Con `functionPerRoute: false`, solo hay un controlador único encargado de renderizar todas tus rutas. Cuando se activa este controlador por primera vez, estarás sujeto a un arranque en frío. Después de eso, todas las demás rutas deberían funcionar sin retraso. Sin embargo, perderás el beneficio de la división de código que proporciona `functionPerRoute: true`. - -:::note -Es importante que comprendas tu plataforma de alojamiento y cómo funciona para elegir la configuración adecuada de `functionPerRoute` para tu proyecto. -::: - ### `edgeMiddleware` Define si se incluirá el código de middleware SSR al realizar la compilación. diff --git a/src/content/docs/ja/reference/adapter-reference.mdx b/src/content/docs/ja/reference/adapter-reference.mdx index 0c1cedbff350c..4ce5749a7338a 100644 --- a/src/content/docs/ja/reference/adapter-reference.mdx +++ b/src/content/docs/ja/reference/adapter-reference.mdx @@ -57,10 +57,6 @@ export interface AstroAdapterFeatures { * Astroミドルウェアと通信するエッジ関数を作成します。 */ edgeMiddleware: boolean; - /** - * SSR専用。各ルートが個別の関数/ファイルになります。 - */ - functionPerRoute: boolean; } export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; @@ -245,7 +241,7 @@ try { ###### `routeData`オプション -レンダリングするルートが事前に分かっている場合は、このオプションで[`routeData`](/ja/reference/integrations-reference/#integrationroutedata-type-reference)を指定できます。これにより、ルートを決定するための[`app.match`](#appmatchrequestメソッド)の内部呼び出しをスキップできます。 +レンダリングするルートが事前に分かっている場合は、このオプションで`routeData`を指定できます。これにより、ルートを決定するための[`app.match`](#appmatchrequestメソッド)の内部呼び出しをスキップできます。 ```js "routeData" const routeData = app.match(request); @@ -335,89 +331,6 @@ export default function createIntegration() { アダプターの機能は、出力されるファイルの内容を変更する一連の機能です。アダプターがこれらの機能を有効にすると、特定のフック内で追加情報を取得できます。 -### `functionPerRoute`機能 - -この機能は、SSR(サーバーサイドレンダリング)を使用する場合にのみ有効になります。デフォルトでは、Astroは単一の`entry.mjs`ファイルを生成し、このファイルが各リクエストに対してレンダリングされたページを出力します。 - -`functionPerRoute`を`true`に設定すると、Astroはプロジェクトで定義された各ルートに対して個別のファイルを作成します。 - -生成される各ファイルは1つのページのみをレンダリングします。これらのページファイルは`dist/pages/`ディレクトリ(または[`outDir`](/ja/reference/configuration-reference/#outdir)で指定されたディレクトリ内の`/pages/`)に出力され、`src/pages/`ディレクトリと同じファイル構造を維持します。 - -例えば、`pages/`ディレクトリ内のファイル構造は、ビルド後の`src/pages/`のページファイルの構造を反映します。 - - -- dist/ - - pages/ - - blog/ - - entry.\_slug\_.astro.mjs - - entry.about.astro.mjs - - entry.index.astro.mjs - - -この機能を有効にするには、アダプターに`true`を渡します。 - -```js title="my-adapter.mjs" ins={9-11} -export default function createIntegration() { - return { - name: '@matthewp/my-adapter', - hooks: { - 'astro:config:done': ({ setAdapter }) => { - setAdapter({ - name: '@matthewp/my-adapter', - serverEntrypoint: '@matthewp/my-adapter/server.js', - adapterFeatures: { - functionPerRoute: true - } - }); - }, - }, - }; -} -``` - -その後、[`astro:build:ssr`](/ja/reference/integrations-reference/#astrobuildssr)フックを使用します。このフックは`entryPoints`オブジェクトを提供し、ページのルートとビルド後に生成された実際のファイルをマッピングします。 - -```js title="my-adapter.mjs" ins={15-19} -export default function createIntegration() { - return { - name: '@matthewp/my-adapter', - hooks: { - 'astro:config:done': ({ setAdapter }) => { - setAdapter({ - name: '@matthewp/my-adapter', - serverEntrypoint: '@matthewp/my-adapter/server.js', - adapterFeatures: { - functionPerRoute: true - } - }); - }, - - 'astro:build:ssr': ({ entryPoints }) => { - for (const [route, entryFile] of entryPoints) { - // routeとentryFileを使用して何かをする - } - } - }, - }; -} -``` - -:::caution -`entryFile`は`URL`型で、ファイルシステム上の実際のファイルパスを表します。つまり、コードが実行されるOSによってパスが変わる可能性があります。 -::: - -#### サーバーレス環境での動作について - -サーバーレス環境で`functionPerRoute: true`を設定すると、各ルートに対して個別のJavaScriptファイル(ハンドラー)が作成されます。このハンドラーは、使用するホスティングプラットフォームによってlambda、function、pageなど、さまざまな名前で呼ばれることがあります。 - -これらの各ルートは、ハンドラーが実行される際に[コールドスタート](https://azure.microsoft.com/ja-jp/blog/understanding-serverless-cold-start/)の影響を受ける可能性があり、これにより多少の遅延が生じることがあります。この遅延の程度はさまざまな要因に左右されます。 - -一方、`functionPerRoute: false`に設定した場合、すべてのルートのレンダリングを1つのハンドラーが担当します。このハンドラーが最初に呼び出されるときにはコールドスタートの影響を受けますが、それ以降のルートは遅延なく機能するはずです。ただし、この設定では`functionPerRoute: true`で得られるコード分割の利点は失われてしまいます。 - -:::note -プロジェクトに最適な`functionPerRoute`の設定を選択するためには、使用するホスティングプラットフォームの仕組みをよく理解することが重要です。 -::: - ### `edgeMiddleware`機能について この機能は、SSR(サーバーサイドレンダリング)のミドルウェアコードをビルド時にバンドル(まとめて)するかどうかを指定します。 diff --git a/src/content/docs/ko/guides/upgrade-to/v5.mdx b/src/content/docs/ko/guides/upgrade-to/v5.mdx index 0004c96a2cd2f..7ad1c774516c5 100644 --- a/src/content/docs/ko/guides/upgrade-to/v5.mdx +++ b/src/content/docs/ko/guides/upgrade-to/v5.mdx @@ -1106,7 +1106,7 @@ function useRoute(route: IntegrationRouteData) { } ``` -[`IntegrationRouteData`에 대한 API 참조](/ko/reference/integrations-reference/#integrationroutedata-타입-참조)를 확인하세요. +`IntegrationRouteData`에 대한 API 참조를 확인하세요. ### 변경됨: `distURL`은 이제 배열입니다 (통합 API) @@ -1133,7 +1133,7 @@ if (route.distURL) { } ``` -[`IntegrationRouteData`에 대한 API 참조](/ko/reference/integrations-reference/#integrationroutedata-타입-참조)를 확인하세요. +`IntegrationRouteData`에 대한 API 참조를 확인하세요. ### 변경됨: `app.render()`에 전달되는 인수 (어댑터 API) diff --git a/src/content/docs/ko/reference/adapter-reference.mdx b/src/content/docs/ko/reference/adapter-reference.mdx index c4781f802909d..972f3db6dcc16 100644 --- a/src/content/docs/ko/reference/adapter-reference.mdx +++ b/src/content/docs/ko/reference/adapter-reference.mdx @@ -319,7 +319,7 @@ return app.render(request, { **기본값:** `app.match(request)`

-렌더링할 경로를 이미 알고 있는 경우 [`integrationRouteData`](/ko/reference/integrations-reference/#integrationroutedata-타입-참조)에 대한 값을 제공하세요. 그렇게 하면 렌더링할 경로를 결정하기 위해 [`app.match`](#appmatch)에 대한 내부 호출을 우회하게 됩니다. +렌더링할 경로를 이미 알고 있는 경우 `integrationRouteData`에 대한 값을 제공하세요. 그렇게 하면 렌더링할 경로를 결정하기 위해 [`app.match`](#appmatch)에 대한 내부 호출을 우회하게 됩니다. ```js "routeData" const routeData = app.match(request); diff --git a/src/content/docs/ko/reference/integrations-reference.mdx b/src/content/docs/ko/reference/integrations-reference.mdx index fabca33a94f56..29d0bea5d8825 100644 --- a/src/content/docs/ko/reference/integrations-reference.mdx +++ b/src/content/docs/ko/reference/integrations-reference.mdx @@ -1076,7 +1076,7 @@ export default {

-**타입:** Map\<IntegrationRouteData, URL\>
+**타입:** Map\IntegrationRouteData, URL\>

@@ -1216,7 +1216,7 @@ export default function myIntegration() {

-**타입:** [`IntegrationRouteData[]`](#integrationroutedata-타입-참조) +**타입:** `IntegrationRouteData[]`

생성된 모든 경로와 연결된 메타데이터 목록입니다. diff --git a/src/content/docs/pt-br/reference/adapter-reference.mdx b/src/content/docs/pt-br/reference/adapter-reference.mdx index 2a8b910a61b0e..302993d5e6480 100644 --- a/src/content/docs/pt-br/reference/adapter-reference.mdx +++ b/src/content/docs/pt-br/reference/adapter-reference.mdx @@ -54,10 +54,6 @@ export interface AstroAdapterFeatures { * Cria uma função na edge que irá se comunicar com o middleware do Astro. */ edgeMiddleware: boolean; - /** - * SSR apenas. Cada rota se torna sua própria função/arquivo. - */ - functionPerRoute: boolean; } export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; @@ -293,89 +289,6 @@ e um erro se o serviço usado para assets não é compatível com o adaptador: Um conjunto de funcionalidades que modificam o resultado dos arquivos emitidos. Quando um adaptador opta por essas funcionalidades, ele irá adquirir informação adicional dentro de hooks específicos. -### `functionPerRoute` - -Essa é uma funcionalidade que é habilitada ao utilizar SSR apenas. Por padrão, Astro emite um único arquivo `entry.mjs`, que é responsável por emitir a página renderizada a cada requisição. - -Quando `functionPerRoute` é `true`, Astro irá ao invés disso criar um arquivo separado para cada rota definida no projeto. - -Cada arquivo emitido irá apenas renderizar uma página. As páginas serão emitidas dentro do diretório `dist/pages/` (ou dentro de um diretório `/pages/` no diretório especificado para [`outDir`](/pt-br/reference/configuration-reference/#outdir)), e os arquivos emitidos irão manter o mesmo caminho de arquivo que o diretório `src/pages/`. - -Os arquivos dentro do diretório `pages/` da build refletirão a estrutura do diretório dos seus arquivos de página em `src/pages/`, por exemplo: - - -- dist/ - - pages/ - - blog/ - - entry.\_slug\_.astro.mjs - - entry.sobre.astro.mjs - - entry.index.astro.mjs - - -Habilite essa funcionalidade passando `true` ao adaptador. - -```js title="meu-adaptador.mjs" ins={9-11} -export default function createIntegration() { - return { - name: '@matthewp/meu-adaptador', - hooks: { - 'astro:config:done': ({ setAdapter }) => { - setAdapter({ - name: '@matthewp/meu-adaptador', - serverEntrypoint: '@matthewp/meu-adaptador/server.js', - adapterFeatures: { - functionPerRoute: true - } - }); - }, - }, - }; -} -``` - -Então, consuma o hook [`astro:build:ssr`](/pt-br/reference/integrations-reference/#astrobuildssr), que irá te dar um objeto `entryPoints` que mapeia uma rota de página ao arquivo físico emitido após a build. - -```js title="meu-adaptador.mjs" ins={15-19} -export default function createIntegration() { - return { - name: '@matthewp/meu-adaptador', - hooks: { - 'astro:config:done': ({ setAdapter }) => { - setAdapter({ - name: '@matthewp/meu-adaptador', - serverEntrypoint: '@matthewp/meu-adaptador/server.js', - adapterFeatures: { - functionPerRoute: true - } - }); - }, - - 'astro:build:ssr': ({ entryPoints }) => { - for (const [route, entryFile] of entryPoints) { - // faça algo com a route e entryFile - } - } - }, - }; -} -``` - -:::caution -O `entryFile` é do tipo `URL` e representa o caminho físico do arquivo no sistema de arquivos. Isso significa que os caminhos mudam com base no SO onde o código é executado. -::: - -#### Ambientes Serverless - -Definir `functionPerRoute: true` em um ambiente serverless cria um arquivo JavaScript (handler) para cada rota. Um handler pode terr nomes diferentes com base na sua plataforma de hospedagem: lambda, function, page, etc. - -Cada uma dessas rotas é sujeita a um [cold start](https://azure.microsoft.com/en-us/blog/understanding-serverless-cold-start/) quando o handler é executado, o que pode causar algum delay. Esse delay é influenciado por diferentes fatores. - -Com `functionPerRoute: false`, há apenas um único handler no comando da renderização de todas as suas rotas. Quando esse handler é ativado pela primeira vez, você estará sujeito a um cold start. E então, todas as outras rotas devem funcionar sem delay. Porém, você irá perder o benefício da separação de código que `functionPerRoute: true` fornece. - -:::note -É importante que você entenda sua plataforma de hospedagem, e como ela funciona, para que você escolha a configuração de `functionPerRoute` apropriada para seu projeto. -::: - ### `edgeMiddleware` Define se algum código de middleware SSR passará por bundle ao ser construído. diff --git a/src/content/docs/zh-cn/guides/upgrade-to/v5.mdx b/src/content/docs/zh-cn/guides/upgrade-to/v5.mdx index 242e3e69e245e..2008d5de60019 100644 --- a/src/content/docs/zh-cn/guides/upgrade-to/v5.mdx +++ b/src/content/docs/zh-cn/guides/upgrade-to/v5.mdx @@ -1108,7 +1108,7 @@ function useRoute(route: IntegrationRouteData) { } ``` -请参阅 [`IntegrationRouteData` 的 API 参考](/zh-cn/reference/integrations-reference/#integrationroutedata-类型参考)。 +请参阅 `IntegrationRouteData` 的 API 参考。 ### 改动:`distURL` 现在是一个数组(集成 API) @@ -1135,7 +1135,7 @@ if (route.distURL) { } ``` -请参阅 [`IntegrationRouteData` 的 API 参考](/zh-cn/reference/integrations-reference/#integrationroutedata-类型参考) +请参阅 `IntegrationRouteData` 的 API 参考 ### 改动:传递给 `app.render()` 的参数(适配器 API) diff --git a/src/content/docs/zh-cn/reference/adapter-reference.mdx b/src/content/docs/zh-cn/reference/adapter-reference.mdx index f0c028a13370a..078a479d40813 100644 --- a/src/content/docs/zh-cn/reference/adapter-reference.mdx +++ b/src/content/docs/zh-cn/reference/adapter-reference.mdx @@ -322,7 +322,7 @@ return app.render(request, { **默认值:** `app.match(request)`

-如果你已经知道要渲染的路由,请为 [`integrationRouteData`](/zh-cn/reference/integrations-reference/#integrationroutedata-类型参考) 提供一个值。这样做将绕过内部调用 [`app.match`](#appmatch) 来确定要渲染的路由。 +如果你已经知道要渲染的路由,请为 `integrationRouteData` 提供一个值。这样做将绕过内部调用 [`app.match`](#appmatch) 来确定要渲染的路由。 ```js "routeData" const routeData = app.match(request); diff --git a/src/content/docs/zh-cn/reference/integrations-reference.mdx b/src/content/docs/zh-cn/reference/integrations-reference.mdx index d7436f179326f..4f53b4ff6334b 100644 --- a/src/content/docs/zh-cn/reference/integrations-reference.mdx +++ b/src/content/docs/zh-cn/reference/integrations-reference.mdx @@ -612,7 +612,7 @@ function setPrerender() {

-**类型:** [`IntegrationResolvedRoute[]`](#integrationroutedata-类型参考) +**类型:** `IntegrationResolvedRoute[]`

一个包含了所有路由及其关联元数据的列表。 @@ -1074,7 +1074,7 @@ export default {

-**类型:** Map\<IntegrationRouteData, URL\>
+**类型:** Map\IntegrationRouteData, URL\>

@@ -1214,7 +1214,7 @@ export default function myIntegration() {

-**类型:** [`IntegrationRouteData[]`](#integrationroutedata-类型参考) +**类型:** `IntegrationRouteData[]`

所有生成的路由及其相关元数据的列表。