From faa227d414ed7ff4b7c2dc2058277f1870b17758 Mon Sep 17 00:00:00 2001 From: Suguru Inatomi Date: Wed, 4 Jun 2025 20:12:35 +0900 Subject: [PATCH] fix: translate ssr.md, hydration.md --- adev-ja/src/content/guide/hydration.en.md | 210 +++++++++++++++++++++ adev-ja/src/content/guide/hydration.md | 156 ++++++++-------- adev-ja/src/content/guide/ssr.md | 214 +++++++++++----------- 3 files changed, 395 insertions(+), 185 deletions(-) create mode 100644 adev-ja/src/content/guide/hydration.en.md diff --git a/adev-ja/src/content/guide/hydration.en.md b/adev-ja/src/content/guide/hydration.en.md new file mode 100644 index 0000000000..af9ce586f3 --- /dev/null +++ b/adev-ja/src/content/guide/hydration.en.md @@ -0,0 +1,210 @@ +# Hydration + +## What is hydration + +Hydration is the process that restores the server-side rendered application on the client. This includes things like reusing the server rendered DOM structures, persisting the application state, transferring application data that was retrieved already by the server, and other processes. + +## Why is hydration important? + +Hydration improves application performance by avoiding extra work to re-create DOM nodes. Instead, Angular tries to match existing DOM elements to the applications structure at runtime and reuses DOM nodes when possible. This results in a performance improvement that can be measured using [Core Web Vitals (CWV)](https://web.dev/learn-core-web-vitals/) statistics, such as reducing the First Input Delay ([FID](https://web.dev/fid/)) and Largest Contentful Paint ([LCP](https://web.dev/lcp/)), as well as Cumulative Layout Shift ([CLS](https://web.dev/cls/)). Improving these numbers also affects things like SEO performance. + +Without hydration enabled, server-side rendered Angular applications will destroy and re-render the application's DOM, which may result in a visible UI flicker. This re-rendering can negatively impact [Core Web Vitals](https://web.dev/learn-core-web-vitals/) like [LCP](https://web.dev/lcp/) and cause a layout shift. Enabling hydration allows the existing DOM to be re-used and prevents a flicker. + +## How do you enable hydration in Angular + +Hydration can be enabled for server-side rendered (SSR) applications only. Follow the [Angular SSR Guide](guide/ssr) to enable server-side rendering first. + +### Using Angular CLI + +If you've used Angular CLI to enable SSR (either by enabling it during application creation or later via `ng add @angular/ssr`), the code that enables hydration should already be included into your application. + +### Manual setup + +If you have a custom setup and didn't use Angular CLI to enable SSR, you can enable hydration manually by visiting your main application component or module and importing `provideClientHydration` from `@angular/platform-browser`. You'll then add that provider to your app's bootstrapping providers list. + +```typescript +import { + bootstrapApplication, + provideClientHydration, +} from '@angular/platform-browser'; +... + +bootstrapApplication(AppComponent, { + providers: [provideClientHydration()] +}); +``` + +Alternatively if you are using NgModules, you would add `provideClientHydration` to your root app module's provider list. + +```typescript +import {provideClientHydration} from '@angular/platform-browser'; +import {NgModule} from '@angular/core'; + +@NgModule({ + declarations: [AppComponent], + exports: [AppComponent], + bootstrap: [AppComponent], + providers: [provideClientHydration()], +}) +export class AppModule {} +``` + +IMPORTANT: Make sure that the `provideClientHydration()` call is also included into a set of providers that is used to bootstrap an application on the **server**. In applications with the default project structure (generated by the `ng new` command), adding a call to the root `AppModule` should be sufficient, since this module is imported by the server module. If you use a custom setup, add the `provideClientHydration()` call to the providers list in the server bootstrap configuration. + +### Verify that hydration is enabled + +After you've configured hydration and have started up your server, load your application in the browser. + +HELPFUL: You will likely need to fix instances of Direct DOM Manipulation before hydration will fully work either by switching to Angular constructs or by using `ngSkipHydration`. See [Constraints](#constraints), [Direct DOM Manipulation](#direct-dom-manipulation), and [How to skip hydration for particular components](#how-to-skip-hydration-for-particular-components) for more details. + +While running an application in dev mode, you can confirm hydration is enabled by opening the Developer Tools in your browser and viewing the console. You should see a message that includes hydration-related stats, such as the number of components and nodes hydrated. Angular calculates the stats based on all components rendered on a page, including those that come from third-party libraries. + +You can also use [Angular DevTools browser extension](tools/devtools) to see hydration status of components on a page. Angular DevTools also allows to enable an overlay to indicate which parts of the page were hydrated. If there is a hydration mismatch error - DevTools would also highlight a component that caused the error. + +## Capturing and replaying events + +When an application is rendered on the server, it is visible in a browser as soon as produced HTML loads. Users may assume that they can interact with the page, but event listeners are not attached until hydration completes. Starting from v18, you can enable the Event Replay feature that allows to capture all events that happen before hydration and replay those events once hydration has completed. You can enable it using the `withEventReplay()` function, for example: + +```typescript +import {provideClientHydration, withEventReplay} from '@angular/platform-browser'; + +bootstrapApplication(App, { + providers: [ + provideClientHydration(withEventReplay()) + ] +}); +``` + +### How event replay works +Event Replay is a feature that improves user experience by capturing user events that were triggered before the hydration process is complete. Then those events are replayed, ensuring none of that interaction was lost. + +The Event Replay is divided into three main phases: + +- **Capturing user interactions**
+Prior to **Hydration**, Event Replay captures and stores all interactions that the user may perform, such as clicks and other browser native events. + +- **Storing events**
+The **Event Contract** keeps in memory all the interactions recorded in the previous step, ensuring that they are not lost for later replay. + +- **Relaunch of events**
+Once **Hydration** is complete, Angular re-invokes the captured events. + +Event replay supports _native browser events_, for example `click`, `mouseover`, and `focusin`. If you'd like to learn more about JSAction, the library that powers event replay, you can read more [on the readme](https://github.com/angular/angular/tree/main/packages/core/primitives/event-dispatch#readme). + +--- + +This feature ensures a consistent user experience, preventing user actions performed before Hydration from being ignored. NOTE: if you have [incremental hydration](guide/incremental-hydration) enabled, event replay is automatically enabled under the hood. + +## Constraints + +Hydration imposes a few constraints on your application that are not present without hydration enabled. Your application must have the same generated DOM structure on both the server and the client. The process of hydration expects the DOM tree to have the same structure in both places. This also includes whitespaces and comment nodes that Angular produces during the rendering on the server. Those whitespaces and nodes must be present in the HTML generated by the server-side rendering process. + +IMPORTANT: The HTML produced by the server side rendering operation **must not** be altered between the server and the client. + +If there is a mismatch between server and client DOM tree structures, the hydration process will encounter problems attempting to match up what was expected to what is actually present in the DOM. Components that do direct DOM manipulation using native DOM APIs are the most common culprit. + +### Direct DOM Manipulation + +If you have components that manipulate the DOM using native DOM APIs or use `innerHTML` or `outerHTML`, the hydration process will encounter errors. Specific cases where DOM manipulation is a problem are situations like accessing the `document`, querying for specific elements, and injecting additional nodes using `appendChild`. Detaching DOM nodes and moving them to other locations will also result in errors. + +This is because Angular is unaware of these DOM changes and cannot resolve them during the hydration process. Angular will expect a certain structure, but it will encounter a different structure when attempting to hydrate. This mismatch will result in hydration failure and throw a DOM mismatch error ([see below](#errors)). + +It is best to refactor your component to avoid this sort of DOM manipulation. Try to use Angular APIs to do this work, if you can. If you cannot refactor this behavior, use the `ngSkipHydration` attribute ([described below](#how-to-skip-hydration-for-particular-components)) until you can refactor into a hydration friendly solution. + +### Valid HTML structure + +There are a few cases where if you have a component template that does not have valid HTML structure, this could result in a DOM mismatch error during hydration. + +As an example, here are some of the most common cases of this issue. + +- `` without a `` +- `
` inside a `

` +- `` inside another `` + +If you are uncertain about whether your HTML is valid, you can use a [syntax validator](https://validator.w3.org/) to check it. + +NOTE: While the HTML standard does not require the `

` element inside tables, modern browsers automatically create a `` element in tables that do not declare one. Because of this inconsistency, always explicitly declare a `` element in tables to avoid hydration errors. + +### Preserve Whitespaces Configuration + +When using the hydration feature, we recommend using the default setting of `false` for `preserveWhitespaces`. If this setting is not in your tsconfig, the value will be `false` and no changes are required. If you choose to enable preserving whitespaces by adding `preserveWhitespaces: true` to your tsconfig, it is possible you may encounter issues with hydration. This is not yet a fully supported configuration. + +HELPFUL: Make sure that this setting is set **consistently** in `tsconfig.server.json` for your server and `tsconfig.app.json` for your browser builds. A mismatched value will cause hydration to break. + +If you choose to set this setting in your tsconfig, we recommend to set it only in `tsconfig.app.json` which by default the `tsconfig.server.json` will inherit it from. + +### Custom or Noop Zone.js are not yet supported + +Hydration relies on a signal from Zone.js when it becomes stable inside an application, so that Angular can start the serialization process on the server or post-hydration cleanup on the client to remove DOM nodes that remained unclaimed. + +Providing a custom or a "noop" Zone.js implementation may lead to a different timing of the "stable" event, thus triggering the serialization or the cleanup too early or too late. This is not yet a fully supported configuration and you may need to adjust the timing of the `onStable` event in the custom Zone.js implementation. + +## Errors + +There are several hydration related errors you may encounter ranging from node mismatches to cases when the `ngSkipHydration` was used on an invalid host node. The most common error case that may occur is due to direct DOM manipulation using native APIs that results in hydration being unable to find or match the expected DOM tree structure on the client that was rendered by the server. The other case you may encounter this type of error was mentioned in the [Valid HTML structure](#valid-html-structure) section earlier. So, make sure the HTML in your templates are using valid structure, and you'll avoid that error case. + +For a full reference on hydration related errors, visit the [Errors Reference Guide](/errors). + +## How to skip hydration for particular components + +Some components may not work properly with hydration enabled due to some of the aforementioned issues, like [Direct DOM Manipulation](#direct-dom-manipulation). As a workaround, you can add the `ngSkipHydration` attribute to a component's tag in order to skip hydrating the entire component. + +```angular-html + +``` + +Alternatively you can set `ngSkipHydration` as a host binding. + +```typescript +@Component({ + ... + host: {ngSkipHydration: 'true'}, +}) +class ExampleComponent {} +``` + +The `ngSkipHydration` attribute will force Angular to skip hydrating the entire component and its children. Using this attribute means that the component will behave as if hydration is not enabled, meaning it will destroy and re-render itself. + +HELPFUL: This will fix rendering issues, but it means that for this component (and its children), you don't get the benefits of hydration. You will need to adjust your component's implementation to avoid hydration-breaking patterns (i.e. Direct DOM Manipulation) to be able to remove the skip hydration annotation. + +The `ngSkipHydration` attribute can only be used on component host nodes. Angular throws an error if this attribute is added to other nodes. + +Keep in mind that adding the `ngSkipHydration` attribute to your root application component would effectively disable hydration for your entire application. Be careful and thoughtful about using this attribute. It is intended as a last resort workaround. Components that break hydration should be considered bugs that need to be fixed. + +## Hydration Timing and Application Stability + +Application stability is an important part of the hydration process. Hydration and any post-hydration processes only occur once the application has reported stability. There are a number of ways that stability can be delayed. Examples include setting timeouts and intervals, unresolved promises, and pending microtasks. In those cases, you may encounter the [Application remains unstable](errors/NG0506) error, which indicates that your app has not yet reached the stable state after 10 seconds. If you're finding that your application is not hydrating right away, take a look at what is impacting application stability and refactor to avoid causing these delays. + +## I18N + +HELPFUL: Support for internationalization with hydration is currently in [developer preview](/reference/releases#developer-preview). By default, Angular will skip hydration for components that use i18n blocks, effectively re-rendering those components from scratch. + +To enable hydration for i18n blocks, you can add [`withI18nSupport`](/api/platform-browser/withI18nSupport) to your `provideClientHydration` call. + +```typescript +import { + bootstrapApplication, + provideClientHydration, + withI18nSupport, +} from '@angular/platform-browser'; +... + +bootstrapApplication(AppComponent, { + providers: [provideClientHydration(withI18nSupport())] +}); +``` + +## Consistent rendering across server-side and client-side +Avoid introducing `@if` blocks and other conditionals that display different content when server-side rendering than client-side rendering, such as using an `@if` block with Angular's `isPlatformBrowser` function. These rendering differences cause layout shifts, negatively impacting end-user experience and core web vitals. + +## Third Party Libraries with DOM Manipulation + +There are a number of third party libraries that depend on DOM manipulation to be able to render. D3 charts is a prime example. These libraries worked without hydration, but they may cause DOM mismatch errors when hydration is enabled. For now, if you encounter DOM mismatch errors using one of these libraries, you can add the `ngSkipHydration` attribute to the component that renders using that library. + +## Third Party Scripts with DOM Manipulation + +Many third party scripts, such as ad trackers and analytics, modify the DOM before hydration can occur. These scripts may cause hydration errors because the page no longer matches the structure expected by Angular. Prefer deferring this type of script until after hydration whenever possible. Consider using [`AfterNextRender`](api/core/afterNextRender) to delay the script until post-hydration processes have occured. + +## Incremental Hydration + +Incremental hydration is an advanced form of hydration that allows for more granular control over when hydration happens. See the [incremental hydration guide](guide/incremental-hydration) for more information. diff --git a/adev-ja/src/content/guide/hydration.md b/adev-ja/src/content/guide/hydration.md index af9ce586f3..cbf9dca963 100644 --- a/adev-ja/src/content/guide/hydration.md +++ b/adev-ja/src/content/guide/hydration.md @@ -1,26 +1,26 @@ -# Hydration +# ハイドレーション -## What is hydration +## ハイドレーションとは {#what-is-hydration} -Hydration is the process that restores the server-side rendered application on the client. This includes things like reusing the server rendered DOM structures, persisting the application state, transferring application data that was retrieved already by the server, and other processes. +ハイドレーションとは、サーバーサイドでレンダリングされたアプリケーションをクライアントで復元するプロセスです。これには、サーバーでレンダリングされたDOM構造の再利用、アプリケーション状態の永続化、サーバーによってすでに取得されたアプリケーションデータの転送、その他のプロセスが含まれます。 -## Why is hydration important? +## ハイドレーションが重要な理由 {#why-is-hydration-important} -Hydration improves application performance by avoiding extra work to re-create DOM nodes. Instead, Angular tries to match existing DOM elements to the applications structure at runtime and reuses DOM nodes when possible. This results in a performance improvement that can be measured using [Core Web Vitals (CWV)](https://web.dev/learn-core-web-vitals/) statistics, such as reducing the First Input Delay ([FID](https://web.dev/fid/)) and Largest Contentful Paint ([LCP](https://web.dev/lcp/)), as well as Cumulative Layout Shift ([CLS](https://web.dev/cls/)). Improving these numbers also affects things like SEO performance. +ハイドレーションは、DOMノードの再作成という余分な作業を回避することで、アプリケーションのパフォーマンスを向上させます。Angularは実行時に既存のDOM要素をアプリケーションの構造に一致させようとし、可能な場合はDOMノードを再利用します。これにより、First Input Delay ([FID](https://web.dev/fid/)) やLargest Contentful Paint ([LCP](https://web.dev/lcp/))、Cumulative Layout Shift ([CLS](https://web.dev/cls/)) の削減など、[Core Web Vitals (CWV)](https://web.dev/learn-core-web-vitals/) の統計を使用して測定できるパフォーマンスが向上します。これらの数値を改善することは、SEOパフォーマンスなどにも良い影響を与えます。 -Without hydration enabled, server-side rendered Angular applications will destroy and re-render the application's DOM, which may result in a visible UI flicker. This re-rendering can negatively impact [Core Web Vitals](https://web.dev/learn-core-web-vitals/) like [LCP](https://web.dev/lcp/) and cause a layout shift. Enabling hydration allows the existing DOM to be re-used and prevents a flicker. +ハイドレーションが有効になっていない場合、サーバーサイドでレンダリングされたAngularアプリケーションは、アプリケーションのDOMを破棄して再レンダリングするため、目に見えるUIのちらつきが発生する場合があります。この再レンダリングは、[LCP](https://web.dev/lcp/) などの [Core Web Vitals](https://web.dev/learn-core-web-vitals/) に悪影響を与え、レイアウトシフトを引き起こす可能性があります。ハイドレーションを有効にすると、既存のDOMを再利用でき、ちらつきを防ぎます。 -## How do you enable hydration in Angular +## Angularでハイドレーションを有効にする方法 {#how-do-you-enable-hydration-in-angular} -Hydration can be enabled for server-side rendered (SSR) applications only. Follow the [Angular SSR Guide](guide/ssr) to enable server-side rendering first. +ハイドレーションは、サーバーサイドレンダリング (SSR) アプリケーションでのみ有効にできます。まず、[Angular SSRガイド](guide/ssr)に従ってサーバーサイドレンダリングを有効にしてください。 -### Using Angular CLI +### Angular CLIを使用する {#using-angular-cli} -If you've used Angular CLI to enable SSR (either by enabling it during application creation or later via `ng add @angular/ssr`), the code that enables hydration should already be included into your application. +Angular CLIを使用してSSRを有効にした場合 (アプリケーション作成時、または後で `ng add @angular/ssr` を介して有効にした場合)、ハイドレーションを有効にするコードはすでにアプリケーションに含まれているはずです。 -### Manual setup +### 手動セットアップ {#manual-setup} -If you have a custom setup and didn't use Angular CLI to enable SSR, you can enable hydration manually by visiting your main application component or module and importing `provideClientHydration` from `@angular/platform-browser`. You'll then add that provider to your app's bootstrapping providers list. +カスタムセットアップを使用しており、Angular CLIを使用してSSRを有効にしなかった場合は、メインアプリケーションコンポーネントまたはモジュールにアクセスし、`@angular/platform-browser` から `provideClientHydration` をインポートすることで、手動でハイドレーションを有効にできます。その後、そのプロバイダーをアプリケーションのブートストラッププロバイダーリストに追加します。 ```typescript import { @@ -34,7 +34,7 @@ bootstrapApplication(AppComponent, { }); ``` -Alternatively if you are using NgModules, you would add `provideClientHydration` to your root app module's provider list. +あるいは、NgModulesを使用している場合は、ルートアプリケーションモジュールのプロバイダーリストに `provideClientHydration` を追加します。 ```typescript import {provideClientHydration} from '@angular/platform-browser'; @@ -49,21 +49,21 @@ import {NgModule} from '@angular/core'; export class AppModule {} ``` -IMPORTANT: Make sure that the `provideClientHydration()` call is also included into a set of providers that is used to bootstrap an application on the **server**. In applications with the default project structure (generated by the `ng new` command), adding a call to the root `AppModule` should be sufficient, since this module is imported by the server module. If you use a custom setup, add the `provideClientHydration()` call to the providers list in the server bootstrap configuration. +IMPORTANT: `provideClientHydration()` の呼び出しが、**サーバー**でアプリケーションをブートストラップするために使用されるプロバイダーセットにも含まれていることを確認してください。デフォルトのプロジェクト構造 ( `ng new` コマンドで生成されたもの) を持つアプリケーションでは、このモジュールはサーバーモジュールによってインポートされるため、ルート `AppModule` への呼び出しを追加するだけで十分です。カスタムセットアップを使用している場合は、サーバーブートストラップ設定のプロバイダーリストに `provideClientHydration()` の呼び出しを追加してください。 -### Verify that hydration is enabled +### ハイドレーションが有効になっていることを確認する {#verify-that-hydration-is-enabled} -After you've configured hydration and have started up your server, load your application in the browser. +ハイドレーションを設定し、サーバーを起動したら、ブラウザでアプリケーションをロードします。 -HELPFUL: You will likely need to fix instances of Direct DOM Manipulation before hydration will fully work either by switching to Angular constructs or by using `ngSkipHydration`. See [Constraints](#constraints), [Direct DOM Manipulation](#direct-dom-manipulation), and [How to skip hydration for particular components](#how-to-skip-hydration-for-particular-components) for more details. +HELPFUL: Angularの構成要素に切り替えるか、`ngSkipHydration` を使用して、ハイドレーションが完全に機能する前に、DOMの直接操作のインスタンスを修正する必要があるでしょう。詳細については、[制約](#constraints)、[DOMの直接操作](#direct-dom-manipulation)、および[特定のコンポーネントのハイドレーションをスキップする方法](#how-to-skip-hydration-for-particular-components)を参照してください。 -While running an application in dev mode, you can confirm hydration is enabled by opening the Developer Tools in your browser and viewing the console. You should see a message that includes hydration-related stats, such as the number of components and nodes hydrated. Angular calculates the stats based on all components rendered on a page, including those that come from third-party libraries. +開発モードでアプリケーションを実行している間は、ブラウザで開発者ツールを開き、コンソールを表示することで、ハイドレーションが有効になっていることを確認できます。ハイドレーションされたコンポーネントとノードの数など、ハイドレーション関連の統計を含むメッセージが表示されるはずです。Angularは、サードパーティライブラリから提供されるものを含め、ページにレンダリングされたすべてのコンポーネントに基づいて統計を計算します。 -You can also use [Angular DevTools browser extension](tools/devtools) to see hydration status of components on a page. Angular DevTools also allows to enable an overlay to indicate which parts of the page were hydrated. If there is a hydration mismatch error - DevTools would also highlight a component that caused the error. +[Angular DevToolsブラウザ拡張機能](tools/devtools)を使用して、ページのコンポーネントのハイドレーションステータスを確認できます。Angular DevToolsでは、ページのどの部分がハイドレーションされたかを示すオーバーレイを有効にもできます。ハイドレーションの不一致エラーがある場合、DevToolsはエラーの原因となったコンポーネントも強調表示します。 -## Capturing and replaying events +## イベントのキャプチャとリプレイ {#capturing-and-replaying-events} -When an application is rendered on the server, it is visible in a browser as soon as produced HTML loads. Users may assume that they can interact with the page, but event listeners are not attached until hydration completes. Starting from v18, you can enable the Event Replay feature that allows to capture all events that happen before hydration and replay those events once hydration has completed. You can enable it using the `withEventReplay()` function, for example: +アプリケーションがサーバーでレンダリングされると、生成されたHTMLがロードされ次第、ブラウザに表示されます。ユーザーはページを操作できると考えるかもしれませんが、ハイドレーションが完了するまでイベントリスナーはアタッチされません。v18以降では、ハイドレーションの前に発生したすべてのイベントをキャプチャし、ハイドレーションが完了した後にそれらのイベントをリプレイできるようにするイベントリプレイ機能を有効にできます。たとえば、`withEventReplay()` 関数を使用して有効にできます。 ```typescript import {provideClientHydration, withEventReplay} from '@angular/platform-browser'; @@ -75,85 +75,85 @@ bootstrapApplication(App, { }); ``` -### How event replay works -Event Replay is a feature that improves user experience by capturing user events that were triggered before the hydration process is complete. Then those events are replayed, ensuring none of that interaction was lost. +### イベントリプレイの仕組み {#how-event-replay-works} +イベントリプレイは、ハイドレーションプロセスが完了する前にトリガーされたユーザーイベントをキャプチャすることで、ユーザー体験を向上させる機能です。その後、それらのイベントがリプレイされ、インタラクションが失われないようにします。 -The Event Replay is divided into three main phases: +イベントリプレイは主に3つのフェーズに分かれています。 -- **Capturing user interactions**
-Prior to **Hydration**, Event Replay captures and stores all interactions that the user may perform, such as clicks and other browser native events. +- **ユーザーインタラクションのキャプチャ**
+**ハイドレーション**の前に、イベントリプレイは、クリックやその他のブラウザネイティブイベントなど、ユーザーが行う可能性のあるすべてのインタラクションをキャプチャして保存します。 -- **Storing events**
-The **Event Contract** keeps in memory all the interactions recorded in the previous step, ensuring that they are not lost for later replay. +- **イベントの保存**
+**イベントコントラクト**は、前のステップで記録されたすべてのインタラクションをメモリに保持し、後でリプレイするために失われないようにします。 -- **Relaunch of events**
-Once **Hydration** is complete, Angular re-invokes the captured events. +- **イベントの再実行**
+**ハイドレーション**が完了すると、Angularはキャプチャされたイベントを再呼び出しします。 -Event replay supports _native browser events_, for example `click`, `mouseover`, and `focusin`. If you'd like to learn more about JSAction, the library that powers event replay, you can read more [on the readme](https://github.com/angular/angular/tree/main/packages/core/primitives/event-dispatch#readme). +イベントリプレイは、`click`、`mouseover`、`focusin` などの _ネイティブブラウザイベント_ をサポートしています。イベントリプレイを強化するライブラリであるJSActionについて詳しく知りたい場合は、[readme](https://github.com/angular/angular/tree/main/packages/core/primitives/event-dispatch#readme) を参照してください。 --- -This feature ensures a consistent user experience, preventing user actions performed before Hydration from being ignored. NOTE: if you have [incremental hydration](guide/incremental-hydration) enabled, event replay is automatically enabled under the hood. +この機能は、ハイドレーションの前に実行されたユーザーアクションが無視されるのを防ぎ、一貫したユーザー体験を保証します。NOTE: [インクリメンタルハイドレーション](guide/incremental-hydration)を有効にしている場合、イベントリプレイは内部的に自動で有効になります。 -## Constraints +## 制約 {#constraints} -Hydration imposes a few constraints on your application that are not present without hydration enabled. Your application must have the same generated DOM structure on both the server and the client. The process of hydration expects the DOM tree to have the same structure in both places. This also includes whitespaces and comment nodes that Angular produces during the rendering on the server. Those whitespaces and nodes must be present in the HTML generated by the server-side rendering process. +ハイドレーションは、ハイドレーションが有効になっていない場合には存在しないいくつかの制約をアプリケーションに課します。アプリケーションは、サーバーとクライアントの両方で同じ生成されたDOM構造を持つ必要があります。ハイドレーションのプロセスは、DOMツリーが両方の場所で同じ構造を持つことを期待します。これには、Angularがサーバーでのレンダリング中に生成する空白やコメントノードも含まれます。これらの空白やノードは、サーバーサイドレンダリングプロセスによって生成されたHTMLに存在する必要があります。 -IMPORTANT: The HTML produced by the server side rendering operation **must not** be altered between the server and the client. +IMPORTANT: サーバーサイドレンダリング操作によって生成されたHTMLは、サーバーとクライアントの間で変更されてはなりません。 -If there is a mismatch between server and client DOM tree structures, the hydration process will encounter problems attempting to match up what was expected to what is actually present in the DOM. Components that do direct DOM manipulation using native DOM APIs are the most common culprit. +サーバーとクライアントのDOMツリー構造に不一致がある場合、ハイドレーションプロセスは、期待されたものと実際にDOMに存在するものを一致させようとするときに問題に遭遇します。ネイティブDOM APIを使用してDOMを直接操作するコンポーネントが最も一般的な原因です。 -### Direct DOM Manipulation +### DOMの直接操作 {#direct-dom-manipulation} -If you have components that manipulate the DOM using native DOM APIs or use `innerHTML` or `outerHTML`, the hydration process will encounter errors. Specific cases where DOM manipulation is a problem are situations like accessing the `document`, querying for specific elements, and injecting additional nodes using `appendChild`. Detaching DOM nodes and moving them to other locations will also result in errors. +ネイティブDOM APIを使用してDOMを操作したり、`innerHTML` または `outerHTML` を使用したりするコンポーネントがある場合、ハイドレーションプロセスはエラーに遭遇します。DOM操作が問題となる具体的なケースは、`document` へのアクセス、特定の要素のクエリ、`appendChild` を使用した追加ノードの注入などです。DOMノードをデタッチして別の場所に移動することもエラーにつながります。 -This is because Angular is unaware of these DOM changes and cannot resolve them during the hydration process. Angular will expect a certain structure, but it will encounter a different structure when attempting to hydrate. This mismatch will result in hydration failure and throw a DOM mismatch error ([see below](#errors)). +これは、AngularがこれらのDOM変更を認識せず、ハイドレーションプロセス中にそれらを解決できないためです。Angularは特定の構造を期待しますが、ハイドレーションを試みるときに異なる構造に遭遇します。この不一致はハイドレーションの失敗につながり、DOM不一致エラー ([下記参照](#errors)) をスローします。 -It is best to refactor your component to avoid this sort of DOM manipulation. Try to use Angular APIs to do this work, if you can. If you cannot refactor this behavior, use the `ngSkipHydration` attribute ([described below](#how-to-skip-hydration-for-particular-components)) until you can refactor into a hydration friendly solution. +このようなDOM操作を避けるために、コンポーネントをリファクタリングするのが最善です。可能であれば、Angular APIを使用して作業してください。この動作をリファクタリングできない場合は、ハイドレーションに適したソリューションにリファクタリングできるまで、`ngSkipHydration` 属性 ([下記参照](#how-to-skip-hydration-for-particular-components)) を使用してください。 -### Valid HTML structure +### 有効なHTML構造 {#valid-html-structure} -There are a few cases where if you have a component template that does not have valid HTML structure, this could result in a DOM mismatch error during hydration. +コンポーネントテンプレートに有効なHTML構造がない場合、ハイドレーション中にDOM不一致エラーが発生する可能性のあるケースがいくつかあります。 -As an example, here are some of the most common cases of this issue. +例として、この問題の最も一般的なケースをいくつか示します。 -- `
` without a `` -- `
` inside a `

` -- `` inside another `` +- `

` のない `
` +- `

` 内の `

` +- 別の `` 内の `` -If you are uncertain about whether your HTML is valid, you can use a [syntax validator](https://validator.w3.org/) to check it. +HTMLが有効かどうか不明な場合は、[構文バリデーター](https://validator.w3.org/)を使用して確認できます。 -NOTE: While the HTML standard does not require the `
` element inside tables, modern browsers automatically create a `` element in tables that do not declare one. Because of this inconsistency, always explicitly declare a `` element in tables to avoid hydration errors. +NOTE: HTML標準ではテーブル内に `` 要素を必須としていませんが、最新のブラウザは `` を宣言していないテーブルに自動的に `` 要素を作成します。この不整合のため、ハイドレーションエラーを避けるために、テーブルでは常に `` 要素を明示的に宣言してください。 -### Preserve Whitespaces Configuration +### preserveWhitespaces設定 {#preserve-whitespaces-configuration} -When using the hydration feature, we recommend using the default setting of `false` for `preserveWhitespaces`. If this setting is not in your tsconfig, the value will be `false` and no changes are required. If you choose to enable preserving whitespaces by adding `preserveWhitespaces: true` to your tsconfig, it is possible you may encounter issues with hydration. This is not yet a fully supported configuration. +ハイドレーション機能を使用する場合、`preserveWhitespaces` のデフォルト設定である `false` を使用することをお勧めします。この設定がtsconfigにない場合、値は `false` であり、変更は不要です。`preserveWhitespaces: true` をtsconfigに追加して空白の保持を有効にすることを選択した場合、ハイドレーションで問題が発生する可能性があります。これはまだ完全にサポートされている構成ではありません。 -HELPFUL: Make sure that this setting is set **consistently** in `tsconfig.server.json` for your server and `tsconfig.app.json` for your browser builds. A mismatched value will cause hydration to break. +HELPFUL: この設定が、サーバーの `tsconfig.server.json` とブラウザビルドの `tsconfig.app.json` で**一貫して**設定されていることを確認してください。値が一致しないと、ハイドレーションが壊れます。 -If you choose to set this setting in your tsconfig, we recommend to set it only in `tsconfig.app.json` which by default the `tsconfig.server.json` will inherit it from. +この設定をtsconfigで設定することを選択した場合、デフォルトで `tsconfig.server.json` が継承する `tsconfig.app.json` のみに設定することをお勧めします。 -### Custom or Noop Zone.js are not yet supported +### カスタムまたはNoop Zone.jsはまだサポートされていません {#custom-or-oop-zonejs-are-not-yet-supported} -Hydration relies on a signal from Zone.js when it becomes stable inside an application, so that Angular can start the serialization process on the server or post-hydration cleanup on the client to remove DOM nodes that remained unclaimed. +ハイドレーションは、アプリケーション内でZone.jsが安定したときにZone.jsからのシグナルに依存しており、これによりAngularはサーバーでシリアル化プロセスを開始したり、クライアントでハイドレーション後のクリーンアップを実行して未請求のDOMノードを削除したりできます。 -Providing a custom or a "noop" Zone.js implementation may lead to a different timing of the "stable" event, thus triggering the serialization or the cleanup too early or too late. This is not yet a fully supported configuration and you may need to adjust the timing of the `onStable` event in the custom Zone.js implementation. +カスタムまたは「noop」Zone.jsの実装を提供すると、「安定」イベントのタイミングが異なり、シリアル化またはクリーンアップが早すぎたり遅すぎたりする可能性があります。これはまだ完全にサポートされている構成ではなく、カスタムZone.js実装の `onStable` イベントのタイミングを調整する必要がある場合があります。 -## Errors +## エラー {#errors} -There are several hydration related errors you may encounter ranging from node mismatches to cases when the `ngSkipHydration` was used on an invalid host node. The most common error case that may occur is due to direct DOM manipulation using native APIs that results in hydration being unable to find or match the expected DOM tree structure on the client that was rendered by the server. The other case you may encounter this type of error was mentioned in the [Valid HTML structure](#valid-html-structure) section earlier. So, make sure the HTML in your templates are using valid structure, and you'll avoid that error case. +ノードの不一致から、`ngSkipHydration` が無効なホストノードで使用されたケースまで、ハイドレーション関連のいくつかのエラーに遭遇する可能性があります。最も一般的なエラーケースは、ネイティブAPIを使用したDOMの直接操作が原因で発生するもので、ハイドレーションがサーバーによってレンダリングされたクライアント上の期待されるDOMツリー構造を見つけたり一致させたりできないというものです。この種のエラーに遭遇するもう1つのケースは、以前の[有効なHTML構造](#valid-html-structure)セクションで述べました。したがって、テンプレート内のHTMLが有効な構造を使用していることを確認すれば、そのエラーケースを回避できます。 -For a full reference on hydration related errors, visit the [Errors Reference Guide](/errors). +ハイドレーション関連のエラーの完全なリファレンスについては、[エラーリファレンスガイド](/errors)を参照してください。 -## How to skip hydration for particular components +## 特定のコンポーネントのハイドレーションをスキップする方法 {#how-to-skip-hydration-for-particular-components} -Some components may not work properly with hydration enabled due to some of the aforementioned issues, like [Direct DOM Manipulation](#direct-dom-manipulation). As a workaround, you can add the `ngSkipHydration` attribute to a component's tag in order to skip hydrating the entire component. +一部のコンポーネントは、[DOMの直接操作](#direct-dom-manipulation)のような前述の問題により、ハイドレーションが有効になっていると正しく機能しない場合があります。回避策として、コンポーネントのタグに `ngSkipHydration` 属性を追加して、コンポーネント全体のハイドレーションをスキップできます。 ```angular-html ``` -Alternatively you can set `ngSkipHydration` as a host binding. +あるいは、`ngSkipHydration` をホストバインディングとして設定できます。 ```typescript @Component({ @@ -163,23 +163,23 @@ Alternatively you can set `ngSkipHydration` as a host binding. class ExampleComponent {} ``` -The `ngSkipHydration` attribute will force Angular to skip hydrating the entire component and its children. Using this attribute means that the component will behave as if hydration is not enabled, meaning it will destroy and re-render itself. +`ngSkipHydration` 属性は、Angularにコンポーネント全体とその子孫のハイドレーションをスキップさせます。この属性を使用すると、コンポーネントはハイドレーションが有効になっていないかのように動作し、自身を破棄して再レンダリングします。 -HELPFUL: This will fix rendering issues, but it means that for this component (and its children), you don't get the benefits of hydration. You will need to adjust your component's implementation to avoid hydration-breaking patterns (i.e. Direct DOM Manipulation) to be able to remove the skip hydration annotation. +HELPFUL: これによりレンダリングの問題は修正されますが、このコンポーネント (およびその子孫) ではハイドレーションの恩恵を受けられないことを意味します。ハイドレーションを壊すパターン (例: DOMの直接操作) を避けるために、コンポーネントの実装を調整して、ハイドレーションスキップのアノテーションを削除できるようにする必要があります。 -The `ngSkipHydration` attribute can only be used on component host nodes. Angular throws an error if this attribute is added to other nodes. +`ngSkipHydration` 属性は、コンポーネントのホストノードでのみ使用できます。この属性が他のノードに追加された場合、Angularはエラーをスローします。 -Keep in mind that adding the `ngSkipHydration` attribute to your root application component would effectively disable hydration for your entire application. Be careful and thoughtful about using this attribute. It is intended as a last resort workaround. Components that break hydration should be considered bugs that need to be fixed. +ルートアプリケーションコンポーネントに `ngSkipHydration` 属性を追加すると、アプリケーション全体のハイドレーションが実質的に無効になることに注意してください。この属性の使用には注意と検討が必要です。これは最後の手段の回避策として意図されています。ハイドレーションを壊すコンポーネントは、修正が必要なバグと見なされるべきです。 -## Hydration Timing and Application Stability +## ハイドレーションのタイミングとアプリケーションの安定性 {#hydration-timing-and-application-stability} -Application stability is an important part of the hydration process. Hydration and any post-hydration processes only occur once the application has reported stability. There are a number of ways that stability can be delayed. Examples include setting timeouts and intervals, unresolved promises, and pending microtasks. In those cases, you may encounter the [Application remains unstable](errors/NG0506) error, which indicates that your app has not yet reached the stable state after 10 seconds. If you're finding that your application is not hydrating right away, take a look at what is impacting application stability and refactor to avoid causing these delays. +アプリケーションの安定性は、ハイドレーションプロセスにおいて重要な部分です。ハイドレーションおよびハイドレーション後のプロセスは、アプリケーションが安定性を報告した後にのみ発生します。安定性が遅延する可能性のある方法はいくつかあります。例としては、タイムアウトとインターバルの設定、未解決のPromise、保留中のマイクロタスクなどがあります。これらの場合、アプリケーションが10秒後に安定状態に達していないことを示す [アプリケーションが不安定なままです](errors/NG0506) エラーに遭遇する可能性があります。アプリケーションがすぐにハイドレーションされない場合は、アプリケーションの安定性に影響を与えているものを見直し、これらの遅延を引き起こさないようにリファクタリングしてください。 -## I18N +## I18N {#i18n} -HELPFUL: Support for internationalization with hydration is currently in [developer preview](/reference/releases#developer-preview). By default, Angular will skip hydration for components that use i18n blocks, effectively re-rendering those components from scratch. +HELPFUL: ハイドレーションによる国際化のサポートは、現在 [開発者プレビュー](/reference/releases#developer-preview) 段階です。デフォルトでは、Angularはi18nブロックを使用するコンポーネントのハイドレーションをスキップし、それらのコンポーネントを最初から再レンダリングします。 -To enable hydration for i18n blocks, you can add [`withI18nSupport`](/api/platform-browser/withI18nSupport) to your `provideClientHydration` call. +i18nブロックのハイドレーションを有効にするには、`provideClientHydration` の呼び出しに [`withI18nSupport`](/api/platform-browser/withI18nSupport) を追加します。 ```typescript import { @@ -194,17 +194,17 @@ bootstrapApplication(AppComponent, { }); ``` -## Consistent rendering across server-side and client-side -Avoid introducing `@if` blocks and other conditionals that display different content when server-side rendering than client-side rendering, such as using an `@if` block with Angular's `isPlatformBrowser` function. These rendering differences cause layout shifts, negatively impacting end-user experience and core web vitals. +## サーバーサイドとクライアントサイドでの一貫したレンダリング {#consistent-rendering-across-server-side-and-client-side} +サーバーサイドレンダリング時とクライアントサイドレンダリング時で異なるコンテンツを表示する `@if` ブロックやその他の条件分岐 (Angularの `isPlatformBrowser` 関数を `@if` ブロックで使用するなど) を導入することは避けてください。これらのレンダリングの違いはレイアウトシフトを引き起こし、ユーザー体験とCore Web Vitalsに悪影響を与えます。 -## Third Party Libraries with DOM Manipulation +## DOM操作を伴うサードパーティライブラリ {#third-party-libraries-with-dom-manipulation} -There are a number of third party libraries that depend on DOM manipulation to be able to render. D3 charts is a prime example. These libraries worked without hydration, but they may cause DOM mismatch errors when hydration is enabled. For now, if you encounter DOM mismatch errors using one of these libraries, you can add the `ngSkipHydration` attribute to the component that renders using that library. +レンダリングのためにDOM操作に依存するサードパーティライブラリが多数存在します。D3チャートはその典型的な例です。これらのライブラリはハイドレーションなしでは機能しましたが、ハイドレーションが有効な場合はDOM不一致エラーを引き起こす可能性があります。現時点では、これらのライブラリのいずれかを使用してDOM不一致エラーが発生した場合、そのライブラリを使用してレンダリングするコンポーネントに `ngSkipHydration` 属性を追加できます。 -## Third Party Scripts with DOM Manipulation +## DOM操作を伴うサードパーティスクリプト {#third-party-scripts-with-dom-manipulation} -Many third party scripts, such as ad trackers and analytics, modify the DOM before hydration can occur. These scripts may cause hydration errors because the page no longer matches the structure expected by Angular. Prefer deferring this type of script until after hydration whenever possible. Consider using [`AfterNextRender`](api/core/afterNextRender) to delay the script until post-hydration processes have occured. +広告トラッカーやアナリティクスなど、多くのサードパーティスクリプトは、ハイドレーションが行われる前にDOMを変更します。これらのスクリプトは、ページがAngularが期待する構造と一致しなくなるため、ハイドレーションエラーを引き起こす可能性があります。可能な限り、この種のスクリプトをハイドレーション後まで遅らせることを推奨します。`AfterNextRender` を使用して、ハイドレーション後のプロセスが発生するまでスクリプトを遅延させることを検討してください。 -## Incremental Hydration +## インクリメンタルハイドレーション {#incremental-hydration} -Incremental hydration is an advanced form of hydration that allows for more granular control over when hydration happens. See the [incremental hydration guide](guide/incremental-hydration) for more information. +インクリメンタルハイドレーションは、ハイドレーションがいつ発生するかをよりきめ細かく制御できる、高度なハイドレーション形式です。詳細については、[インクリメンタルハイドレーションガイド](guide/incremental-hydration)を参照してください。 diff --git a/adev-ja/src/content/guide/ssr.md b/adev-ja/src/content/guide/ssr.md index 6d72ec6e65..510d913547 100644 --- a/adev-ja/src/content/guide/ssr.md +++ b/adev-ja/src/content/guide/ssr.md @@ -1,32 +1,32 @@ -# Server and hybrid rendering +# サーバーとハイブリッドレンダリング -Angular ships all applications as client-side rendered (CSR) by default. While this approach delivers a initial payload that's lightweight, it introduces trade-offs including slower load times, degraded performance metrics, and higher resource demands since the user's device performs most of the computations. As a result, many applications achieve significant performance improvements by integrating server-side rendering (SSR) into a hybrid rendering strategy. +Angularはデフォルトですべてのアプリケーションをクライアントサイドレンダリング (CSR) として提供します。このアプローチは軽量な初期ペイロードを提供しますが、ユーザーのデバイスがほとんどの計算をするため、ロード時間の遅延、パフォーマンス指標の低下、リソース要件の増加といったトレードオフを伴います。その結果、多くのアプリケーションはサーバーサイドレンダリング (SSR) をハイブリッドレンダリング戦略に統合することで、大幅なパフォーマンス向上を実現しています。 -## What is hybrid rendering? +## ハイブリッドレンダリングとは? {#what-is-hybrid-rendering} -Hybrid rendering allows developers to leverage the benefits of server-side rendering (SSR), pre-rendering (also known as "static site generation" or SSG) and client-side rendering (CSR) to optimize your Angular application. It gives you fine-grained control over how your different parts of your app is rendered to give your users the best experience possible. +ハイブリッドレンダリングにより、開発者はサーバーサイドレンダリング (SSR)、プリレンダリング (「静的サイト生成」またはSSGとも呼ばれる)、およびクライアントサイドレンダリング (CSR) の利点を活用して、Angularアプリケーションを最適化できます。これにより、アプリケーションのさまざまな部分がどのようにレンダリングされるかをきめ細かく制御し、ユーザーに可能な限り最高のユーザー体験を提供できます。 -## Setting up hybrid rendering +## ハイブリッドレンダリングのセットアップ {#setting-up-hybrid-rendering} -You can create a **new** project with hybrid rendering by using the server-side rendering flag (i.e., `--ssr`) with the Angular CLI `ng new` command: +Angular CLIの `ng new` コマンドでサーバーサイドレンダリングフラグ (つまり、`--ssr`) を使用すると、ハイブリッドレンダリングを有効にした**新しい**プロジェクトを作成できます。 ```shell ng new --ssr ``` -You can also enable hybrid rendering by adding server-side rendering to an existing project with the `ng add` command: +既存のプロジェクトにサーバーサイドレンダリングを追加して、ハイブリッドレンダリングを有効にできます。 ```shell ng add @angular/ssr ``` -NOTE: By default, Angular prerenders your entire application and generates a server file. To disable this and create a fully static app, set `outputMode` to `static`. To enable SSR, update the server routes to use `RenderMode.Server`. For more details, see [`Server routing`](#server-routing) and [`Generate a fully static application`](#generate-a-fully-static-application). +NOTE: デフォルトでは、Angularはアプリケーション全体をプリレンダリングし、サーバーファイルを生成します。これを無効にして完全に静的なアプリケーションを作成するには、`outputMode` を `static` に設定します。SSRを有効にするには、サーバーのルートを更新して `RenderMode.Server` を使用します。詳細については、[`サーバールーティング`](#server-routing) および [`完全に静的なアプリケーションを生成する`](#generate-a-fully-static-application) を参照してください。 -## Server routing +## サーバールーティング {#server-routing} -### Configuring server routes +### サーバールートの設定 {#configuring-server-routes} -You can create a server route config by declaring an array of [`ServerRoute`](api/ssr/ServerRoute 'API reference') objects. This configuration typically lives in a file named `app.routes.server.ts`. +[`ServerRoute`](api/ssr/ServerRoute 'API reference') オブジェクトの配列を宣言することで、サーバールート設定を作成できます。この設定は通常、`app.routes.server.ts` というファイルに記述されます。 ```typescript // app.routes.server.ts @@ -34,25 +34,25 @@ import { RenderMode, ServerRoute } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { - path: '', // This renders the "/" route on the client (CSR) + path: '', // これはクライアントで "/" ルートをレンダリングします (CSR) renderMode: RenderMode.Client, }, { - path: 'about', // This page is static, so we prerender it (SSG) + path: 'about', // このページは静的なので、プリレンダリングします (SSG) renderMode: RenderMode.Prerender, }, { - path: 'profile', // This page requires user-specific data, so we use SSR + path: 'profile', // このページはユーザー固有のデータを必要とするため、SSRを使用します renderMode: RenderMode.Server, }, { - path: '**', // All other routes will be rendered on the server (SSR) + path: '**', // 他のすべてのルートはサーバーでレンダリングされます (SSR) renderMode: RenderMode.Server, }, ]; ``` -You can add this config to your application with [`provideServerRendering`](api/ssr/provideServerRendering 'API reference') using the [`withRoutes`](api/ssr/withRoutes 'API reference') function: +この設定は、[`withRoutes`](api/ssr/withRoutes 'API reference') 関数を使用して [`provideServerRendering`](api/ssr/provideServerRendering 'API reference') でアプリケーションに追加できます。 ```typescript import { provideServerRendering, withRoutes } from '@angular/ssr'; @@ -62,12 +62,12 @@ import { serverRoutes } from './app.routes.server'; const serverConfig: ApplicationConfig = { providers: [ provideServerRendering(withRoutes(serverRoutes)), - // ... other providers ... + // ... その他のプロバイダー ... ] }; ``` -When using the [App shell pattern](ecosystem/service-workers/app-shell), you must specify the component to be used as the app shell for client-side rendered routes. To do this, use the [`withAppShell`](api/ssr/withAppShell 'API reference') fetaure: +[App shellパターン](ecosystem/service-workers/app-shell)を使用する場合、クライアントサイドレンダリングされたルートのApp shellとして使用するコンポーネントを指定する必要があります。これを行うには、[`withAppShell`](api/ssr/withAppShell 'API reference') 機能を使用します。 ```typescript import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr'; @@ -79,66 +79,66 @@ const serverConfig: ApplicationConfig = { withRoutes(serverRoutes), withAppShell(AppShellComponent), ), - // ... other providers ... + // ... その他のプロバイダー ... ] }; ``` -### Rendering modes +### レンダリングモード {#rendering-modes} -The server routing configuration lets you specify how each route in your application should render by setting a [`RenderMode`](api/ssr/RenderMode 'API reference'): +サーバールーティング設定では、[`RenderMode`](api/ssr/RenderMode 'API reference') を設定することで、アプリケーションの各ルートをどのようにレンダリングするかを指定できます。 -| Rendering mode | Description | -| ------------------- | ----------------------------------------------------------------------------------------------------------- | -| **Server (SSR)** | Renders the application on the server for each request, sending a fully populated HTML page to the browser. | -| **Client (CSR)** | Renders the application in the browser. This is the default Angular behavior. | -| **Prerender (SSG)** | Prerenders the application at build time, generating static HTML files for each route. | +| レンダリングモード | 説明 | +| ------------------- | ---------------------------------------------------------------------------------------------------- | +| **Server (SSR)** | 各リクエストに対してアプリケーションをサーバーでレンダリングし、完全にデータが投入されたHTMLページをブラウザに送信します。 | +| **Client (CSR)** | アプリケーションをブラウザでレンダリングします。これはAngularのデフォルトの動作です。 | +| **Prerender (SSG)** | ビルド時にアプリケーションをプリレンダリングし、各ルートの静的HTMLファイルを生成します。 | -#### Choosing a rendering mode +#### レンダリングモードの選択 {#choosing-a-rendering-mode} -Each rendering mode has different benefits and drawbacks. You can choose rendering modes based on the specific needs of your application. +各レンダリングモードには異なる利点と欠点があります。アプリケーションの特定のニーズに基づいてレンダリングモードを選択できます。 -##### Client-side rendering +##### クライアントサイドレンダリング {#client-side-rendering} -Client-side rendering has the simplest development model, as you can write code that assumes it always runs in a web browser. This lets you use a wide range of client-side libraries that also assume they run in a browser. +クライアントサイドレンダリングは、常にWebブラウザで実行されることを前提としたコードを記述できるため、最もシンプルな開発モデルです。これにより、ブラウザで実行されることを前提とした幅広いクライアントサイドライブラリを使用できます。 -Client-side rendering generally has worse performance than other rendering modes, as it must download, parse, and execute your page's JavaScript before the user can see any rendered content. If your page fetches more data from the server as it renders, users also have to wait for those additional requests before they can view the complete content. +クライアントサイドレンダリングは、ユーザーがレンダリングされたコンテンツを見る前にページのJavaScriptをダウンロード、解析、実行する必要があるため、一般的に他のレンダリングモードよりもパフォーマンスが劣ります。ページがレンダリング中にサーバーからさらにデータを取得する場合、ユーザーは完全なコンテンツを表示する前にそれらの追加リクエストを待つ必要があります。 -If your page is indexed by search crawlers, client-side rendering may negatively affect search engine optimization (SEO), as search crawlers have limits to how much JavaScript they execute when indexing a page. +ページが検索クローラーによってインデックス付けされる場合、検索クローラーはページのインデックス付け時に実行するJavaScriptの量に制限があるため、クライアントサイドレンダリングは検索エンジン最適化 (SEO) に悪影響を与える可能性があります。 -When client-side rendering, the server does not need to do any work to render a page beyond serving static JavaScript assets. You may consider this factor if server cost is a concern. +クライアントサイドレンダリングの場合、サーバーは静的なJavaScriptアセットを配信する以外に、ページをレンダリングするための作業をする必要がありません。サーバーコストが懸念される場合は、この要素を考慮してもよいでしょう。 -Applications that support installable, offline experiences with [service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can rely on client-side rendering without needing to communicate with a server. +Service Workerによるインストール可能でオフラインのユーザー体験をサポートするアプリケーションは、サーバーと通信することなくクライアントサイドレンダリングに依存できます。 -##### Server-side rendering +##### サーバーサイドレンダリング {#server-side-rendering} -Server-side rendering offers faster page loads than client-side rendering. Instead of waiting for JavaScript to download and run, the server directly renders an HTML document upon receiving a request from the browser. The user experiences only the latency necessary for the server to fetch data and render the requested page. This mode also eliminates the need for additional network requests from the browser, as your code can fetch data during rendering on the server. +サーバーサイドレンダリングは、クライアントサイドレンダリングよりも高速なページロードを提供します。JavaScriptのダウンロードと実行を待つ代わりに、サーバーはブラウザからのリクエストを受信すると、直接HTMLドキュメントをレンダリングします。ユーザーは、サーバーがデータを取得し、要求されたページをレンダリングするために必要な遅延のみを経験します。このモードでは、コードがサーバーでのレンダリング中にデータを取得できるため、ブラウザからの追加のネットワークリクエストも不要になります。 -Server-side rendering generally has excellent search engine optimization (SEO), as search crawlers receive a fully rendered HTML document. +サーバーサイドレンダリングは、検索クローラーが完全にレンダリングされたHTMLドキュメントを受け取るため、一般的に優れた検索エンジン最適化 (SEO) を実現します。 -Server-side rendering requires you to author code that does not strictly depend on browser APIs and limits your selection of JavaScript libraries that assume they run in a browser. +サーバーサイドレンダリングでは、ブラウザAPIに厳密に依存しないコードを作成する必要があり、ブラウザで実行されることを前提としたJavaScriptライブラリの選択が制限されます。 -When server-side rendering, your server runs Angular to produce an HTML response for every request which may increase server hosting costs. +サーバーサイドレンダリングの場合、サーバーはAngularを実行してすべてのリクエストに対してHTMLレスポンスを生成するため、サーバーのホスティングコストが増加する可能性があります。 -##### Build-time prerendering +##### ビルド時プリレンダリング {#build-time-prerendering} -Prerendering offers faster page loads than both client-side rendering and server-side rendering. Because prerendering creates HTML documents at _build-time_, the server can directly respond to requests with the static HTML document without any additional work. +プリレンダリングは、クライアントサイドレンダリングとサーバーサイドレンダリングの両方よりも高速なページロードを提供します。プリレンダリングは_ビルド時_にHTMLドキュメントを作成するため、サーバーは追加の作業なしに静的なHTMLドキュメントで直接リクエストに応答できます。 -Prerendering requires that all information necessary to render a page is available at _build-time_. This means that prerendered pages cannot include any data to the specific user loading the page. Prerendering is primarily useful for pages that are the same for all users of your application. +プリレンダリングでは、ページをレンダリングするために必要なすべての情報が_ビルド時_に利用可能である必要があります。これは、プリレンダリングされたページに、ページをロードする特定のユーザーに関するデータを含めることができないことを意味します。プリレンダリングは、アプリケーションのすべてのユーザーにとって同じであるページに主に役立ちます。 -Because prerendering occurs at build-time, it may add significant time to your production builds. Using [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') to produce a large number of HTML documents may affect the total file size of your deployments, and thus lead to slower deployments. +プリレンダリングはビルド時に行われるため、本番ビルドにかなりの時間を追加する可能性があります。[`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') を使用して多数のHTMLドキュメントを生成すると、デプロイの合計ファイルサイズに影響を与え、デプロイが遅くなる可能性があります。 -Prerendering generally has excellent search engine optimization (SEO), as search crawlers receive a fully rendered HTML document. +プリレンダリングは、検索クローラーが完全にレンダリングされたHTMLドキュメントを受け取るため、一般的に優れた検索エンジン最適化 (SEO) を実現します。 -Prerendering requires you to author code that does not strictly depend on browser APIs and limits your selection of JavaScript libraries that assume they run in a browser. +プリレンダリングでは、ブラウザAPIに厳密に依存しないコードを作成する必要があり、ブラウザで実行されることを前提としたJavaScriptライブラリの選択が制限されます。 -Prerendering incurs extremely little overhead per server request, as your server responds with static HTML documents. Static files are also easily cached by Content Delivery Networks (CDNs), browsers, and intermediate caching layers for even faster subsequent page loads. Fully static sites can also be deployed solely through a CDN or static file server, eliminating the need to maintain a custom server runtime for your application. This enhances scalability by offloading work from an application web server, making it particularly beneficial for high-traffic applications. +プリレンダリングは、サーバーが静的なHTMLドキュメントで応答するため、サーバーリクエストあたりのオーバーヘッドが非常に少なくなります。静的ファイルは、コンテンツデリバリーネットワーク (CDN)、ブラウザ、および中間キャッシュレイヤーによって簡単にキャッシュされ、その後のページロードをさらに高速化できます。完全に静的なサイトは、CDNまたは静的ファイルサーバーのみを介したデプロイもでき、アプリケーション用のカスタムサーバー実行時を維持する必要がなくなります。これにより、アプリケーションWebサーバーからの作業をオフロードすることでスケーラビリティが向上し、トラフィックの多いアプリケーションにとって特に有益です。 -NOTE: When using Angular service worker, the first request is server-rendered, but all subsequent requests are handled by the service worker and rendered client-side. +NOTE: Angular Service Workerを使用する場合、最初のリクエストはサーバーレンダリングされますが、それ以降のすべてのリクエストはService Workerによって処理され、クライアントサイドでレンダリングされます。 -### Setting headers and status codes +### ヘッダーとステータスコードの設定 {#setting-headers-and-status-codes} -You can set custom headers and status codes for individual server routes using the `headers` and `status` properties in the `ServerRoute` configuration. +`ServerRoute` 設定の `headers` および `status` プロパティを使用して、個々のサーバールートにカスタムヘッダーとステータスコードを設定できます。 ```typescript // app.routes.server.ts @@ -153,33 +153,33 @@ export const serverRoutes: ServerRoute[] = [ }, status: 201, }, - // ... other routes + // ... その他のルート ]; ``` -### Redirects +### リダイレクト {#redirects} -Angular handles redirects specified by the [`redirectTo`](api/router/Route#redirectTo 'API reference') property in route configurations, differently on the server-side. +Angularは、ルート設定の [`redirectTo`](api/router/Route#redirectTo 'API reference') プロパティで指定されたリダイレクトを、サーバーサイドでは異なる方法で処理します。 -**Server-Side Rendering (SSR)** -Redirects are performed using standard HTTP redirects (e.g., 301, 302) within the server-side rendering process. +**サーバーサイドレンダリング (SSR)** +リダイレクトは、サーバーサイドレンダリングプロセス内で標準的なHTTPリダイレクト (例: 301、302) を使用して実行されます。 -**Prerendering (SSG)** -Redirects are implemented as "soft redirects" using [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#refresh) tags in the prerendered HTML. +**プリレンダリング (SSG)** +リダイレクトは、プリレンダリングされたHTML内の [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#refresh) タグを使用して「ソフトリダイレクト」として実装されます。 -### Customizing build-time prerendering (SSG) +### ビルド時プリレンダリング (SSG) のカスタマイズ {#customizing-build-time-prerendering-ssg} -When using [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), you can specify several configuration options to customize the prerendering and serving process. +[`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference') を使用する場合、プリレンダリングと提供プロセスをカスタマイズするためのいくつかの設定オプションを指定できます。 -#### Parameterized routes +#### パラメーター化されたルート {#parameterized-routes} -For each route with [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), you can specify a [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') function. This function lets you control which specific parameters produce separate prerendered documents. +[`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference') を持つ各ルートについて、[`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') 関数を指定できます。この関数を使用すると、どの特定のパラメーターが個別のプリレンダリングされたドキュメントを生成するかを制御できます。 -The [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') function returns a `Promise` that resolves to an array of objects. Each object is a key-value map of route parameter name to value. For example, if you define a route like `post/:id`, `getPrerenderParams ` could return the array `[{id: 123}, {id: 456}]`, and thus render separate documents for `post/123` and `post/456`. +[`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') 関数は、オブジェクトの配列に解決される `Promise` を返します。各オブジェクトは、ルートパラメーター名から値へのキーと値のマップです。たとえば、`post/:id` のようなルートを定義した場合、`getPrerenderParams` は配列 `[{id: 123}, {id: 456}]` を返し、`post/123` と `post/456` の個別のドキュメントをレンダリングできます。 -The body of [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') can use Angular's [`inject`](api/core/inject 'API reference') function to inject dependencies and perform any work to determine which routes to prerender. This typically includes making requests to fetch data to construct the array of parameter values. +[`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') の本体は、Angularの [`inject`](api/core/inject 'API reference') 関数を使用して依存性を注入し、どのルートをプリレンダリングするかを決定するための任意の作業ができます。これには通常、パラメーター値の配列を構築するためにデータを取得するリクエストを行うことが含まれます。 -You can also use this function with catch-all routes (e.g., `/**`), where the parameter name will be `"**"` and the return value will be the segments of the path, such as `foo/bar`. These can be combined with other parameters (e.g., `/post/:id/**`) to handle more complex route configuration. +この関数は、キャッチオールルート (例: `/**`) でも使用できます。この場合、パラメーター名は `"**"` となり、戻り値は `foo/bar` のようなパスのセグメントになります。これらは他のパラメーター (例: `/post/:id/**`) と組み合わせて、より複雑なルート設定を処理できます。 ```ts // app.routes.server.ts @@ -191,9 +191,9 @@ export const serverRoutes: ServerRoute[] = [ renderMode: RenderMode.Prerender, async getPrerenderParams() { const dataService = inject(PostService); - const ids = await dataService.getIds(); // Assuming this returns ['1', '2', '3'] + const ids = await dataService.getIds(); // これは ['1', '2', '3'] を返すと仮定します - return ids.map(id => ({ id })); // Generates paths like: /post/1, /post/2, /post/3 + return ids.map(id => ({ id })); // /post/1, /post/2, /post/3 のようなパスを生成します }, }, { @@ -203,25 +203,25 @@ export const serverRoutes: ServerRoute[] = [ return [ { id: '1', '**': 'foo/3' }, { id: '2', '**': 'bar/4' }, - ]; // Generates paths like: /post/1/foo/3, /post/2/bar/4 + ]; // /post/1/foo/3, /post/2/bar/4 のようなパスを生成します }, }, ]; ``` -Because [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') exclusively applies to [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), this function always runs at _build-time_. `getPrerenderParams` must not rely on any browser-specific or server-specific APIs for data. +[`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') は [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference') にのみ適用されるため、この関数は常に_ビルド時_に実行されます。`getPrerenderParams` は、データのためにブラウザ固有またはサーバー固有のAPIに依存してはなりません。 -IMPORTANT: When using [`inject`](api/core/inject 'API reference') inside `getPrerenderParams`, please remember that `inject` must be used synchronously. It cannot be invoked within asynchronous callbacks or following any `await` statements. For more information, refer to [`runInInjectionContext`](api/core/runInInjectionContext). +IMPORTANT: `getPrerenderParams` 内で `inject` を使用する場合、`inject` は同期的に使用する必要があることに注意してください。非同期コールバック内や `await` ステートメントの後に呼び出すことはできません。詳細については、[`runInInjectionContext`](api/core/runInInjectionContext) を参照してください。 -#### Fallback strategies +#### フォールバック戦略 {#fallback-strategies} -When using [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference') mode, you can specify a fallback strategy to handle requests for paths that haven't been prerendered. +[`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference') モードを使用する場合、プリレンダリングされていないパスへのリクエストを処理するためのフォールバック戦略を指定できます。 -The available fallback strategies are: +利用可能なフォールバック戦略は次のとおりです。 -- **Server:** Falls back to server-side rendering. This is the **default** behavior if no `fallback` property is specified. -- **Client:** Falls back to client-side rendering. -- **None:** No fallback. Angular will not handle requests for paths that are not prerendered. +- **Server:** サーバーサイドレンダリングにフォールバックします。これは、`fallback` プロパティが指定されていない場合の**デフォルト**の動作です。 +- **Client:** クライアントサイドレンダリングにフォールバックします。 +- **None:** フォールバックなし。Angularは、プリレンダリングされていないパスへのリクエストを処理しません。 ```typescript // app.routes.server.ts @@ -231,22 +231,22 @@ export const serverRoutes: ServerRoute[] = [ { path: 'post/:id', renderMode: RenderMode.Prerender, - fallback: PrerenderFallback.Client, // Fallback to CSR if not prerendered + fallback: PrerenderFallback.Client, // プリレンダリングされていない場合はCSRにフォールバック async getPrerenderParams() { - // This function returns an array of objects representing prerendered posts at the paths: - // `/post/1`, `/post/2`, and `/post/3`. - // The path `/post/4` will utilize the fallback behavior if it's requested. + // この関数は、/post/1、/post/2、/post/3 のパスで + // プリレンダリングされた投稿を表すオブジェクトの配列を返します。 + // /post/4 のパスがリクエストされた場合、フォールバック動作が利用されます。 return [{ id: 1 }, { id: 2 }, { id: 3 }]; }, }, ]; ``` -## Authoring server-compatible components +## サーバー互換コンポーネントの作成 {#authoring-server-compatible-components} -Some common browser APIs and capabilities might not be available on the server. Applications cannot make use of browser-specific global objects like `window`, `document`, `navigator`, or `location` as well as certain properties of `HTMLElement`. +一部の一般的なブラウザAPIと機能は、サーバーでは利用できない場合があります。アプリケーションは、`window`、`document`、`navigator`、`location` などのブラウザ固有のグローバルオブジェクトや、`HTMLElement` の特定のプロパティを使用できません。 -In general, code which relies on browser-specific symbols should only be executed in the browser, not on the server. This can be enforced through the [`afterEveryRender`](api/core/afterEveryRender) and [`afterNextRender`](api/core/afterNextRender) lifecycle hooks. These are only executed on the browser and skipped on the server. +一般に、ブラウザ固有のシンボルに依存するコードは、サーバーではなくブラウザでのみ実行されるべきです。これは、[`afterEveryRender`](api/core/afterEveryRender) および [`afterNextRender`](api/core/afterNextRender) ライフサイクルフックによって強制できます。これらはブラウザでのみ実行され、サーバーではスキップされます。 ```angular-ts import { Component, ViewChild, afterNextRender } from '@angular/core'; @@ -260,20 +260,20 @@ export class MyComponent { constructor() { afterNextRender(() => { - // Safe to check `scrollHeight` because this will only run in the browser, not the server. + // これはサーバーではなくブラウザでのみ実行されるため、`scrollHeight` のチェックは安全です。 console.log('content height: ' + this.contentRef.nativeElement.scrollHeight); }); } } ``` -## Accessing Request and Response via DI +## DIを介したリクエストとレスポンスへのアクセス {#accessing-request-and-response-via-di} -The `@angular/core` package provides several tokens for interacting with the server-side rendering environment. These tokens give you access to crucial information and objects within your Angular application during SSR. +`@angular/core` パッケージは、サーバーサイドレンダリング環境と対話するためのいくつかのトークンを提供します。これらのトークンにより、SSR中にAngularアプリケーション内で重要な情報とオブジェクトにアクセスできます。 -- **[`REQUEST`](api/core/REQUEST 'API reference'):** Provides access to the current request object, which is of type [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) from the Web API. This allows you to access headers, cookies, and other request information. -- **[`RESPONSE_INIT`](api/core/RESPONSE_INIT 'API reference'):** Provides access to the response initialization options, which is of type [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#parameters) from the Web API. This allows you to set headers and the status code for the response dynamically. Use this token to set headers or status codes that need to be determined at runtime. -- **[`REQUEST_CONTEXT`](api/core/REQUEST_CONTEXT 'API reference'):** Provides access to additional context related to the current request. This context can be passed as the second parameter of the [`handle`](api/ssr/AngularAppEngine#handle 'API reference') function. Typically, this is used to provide additional request-related information that is not part of the standard Web API. +- **[`REQUEST`](api/core/REQUEST 'API reference'):** Web APIの [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) 型である現在のリクエストオブジェクトへのアクセスを提供します。これにより、ヘッダー、Cookie、その他のリクエスト情報にアクセスできます。 +- **[`RESPONSE_INIT`](api/core/RESPONSE_INIT 'API reference'):** Web APIの [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#parameters) 型であるレスポンス初期化オプションへのアクセスを提供します。これにより、レスポンスのヘッダーとステータスコードを動的に設定できます。このトークンを使用して、実行時に決定する必要があるヘッダーまたはステータスコードを設定します。 +- **[`REQUEST_CONTEXT`](api/core/REQUEST_CONTEXT 'API reference'):** 現在のリクエストに関連する追加のコンテキストへのアクセスを提供します。このコンテキストは、[`handle`](api/ssr/AngularAppEngine#handle 'API reference') 関数の2番目のパラメーターとして渡すことができます。通常、これは標準のWeb APIの一部ではない追加のリクエスト関連情報を提供するために使用されます。 ```angular-ts import { inject, REQUEST } from '@angular/core'; @@ -290,20 +290,20 @@ export class MyComponent { } ``` -IMPORTANT: The above tokens will be `null` in the following scenarios: +IMPORTANT: 上記のトークンは、次のシナリオでは `null` になります。 -- During the build processes. -- When the application is rendered in the browser (CSR). -- When performing static site generation (SSG). -- During route extraction in development (at the time of the request). +- ビルドプロセス中。 +- アプリケーションがブラウザでレンダリングされるとき (CSR)。 +- 静的サイト生成 (SSG) を実行するとき。 +- 開発中のルート抽出時 (リクエスト時)。 -## Generate a fully static application +## 完全に静的なアプリケーションを生成する {#generate-a-fully-static-application} -By default, Angular prerenders your entire application and generates a server file for handling requests. This allows your app to serve pre-rendered content to users. However, if you prefer a fully static site without a server, you can opt out of this behavior by setting the `outputMode` to `static` in your `angular.json` configuration file. +デフォルトでは、Angularはアプリケーション全体をプリレンダリングし、リクエストを処理するためのサーバーファイルを生成します。これにより、アプリケーションはプリレンダリングされたコンテンツをユーザーに提供できます。ただし、サーバーなしで完全に静的なサイトを希望する場合は、`angular.json` 設定ファイルで `outputMode` を `static` に設定することで、この動作を無効にできます。 -When `outputMode` is set to `static`, Angular generates pre-rendered HTML files for each route at build time, but it does not generate a server file or require a Node.js server to serve the app. This is useful for deploying to static hosting providers where a backend server is not needed. +`outputMode` が `static` に設定されている場合、Angularはビルド時に各ルートのプリレンダリングされたHTMLファイルを生成しますが、サーバーファイルを生成したり、アプリケーションを提供するためにNode.jsサーバーを必要としたりしません。これは、バックエンドサーバーが不要な静的ホスティングプロバイダーにデプロイする場合に便利です。 -To configure this, update your `angular.json` file as follows: +これを設定するには、`angular.json` ファイルを次のように更新します。 ```json { @@ -321,11 +321,11 @@ To configure this, update your `angular.json` file as follows: } ``` -## Caching data when using HttpClient +## HttpClient使用時のデータキャッシュ {#caching-data-when-using-httpclient} -[`HttpClient`](api/common/http/HttpClient) cached outgoing network requests when running on the server. This information is serialized and transferred to the browser as part of the initial HTML sent from the server. In the browser, `HttpClient` checks whether it has data in the cache and if so, reuses it instead of making a new HTTP request during initial application rendering. `HttpClient` stops using the cache once an application becomes [stable](api/core/ApplicationRef#isStable) while running in a browser. +[`HttpClient`](api/common/http/HttpClient) は、サーバーで実行されているときに送信ネットワークリクエストをキャッシュします。この情報はシリアル化され、サーバーから送信される初期HTMLの一部としてブラウザに転送されます。ブラウザでは、`HttpClient` はキャッシュにデータがあるかどうかを確認し、ある場合は、初期アプリケーションレンダリング中に新しいHTTPリクエストを行う代わりにそれを再利用します。`HttpClient` は、ブラウザで実行中にアプリケーションが[安定](api/core/ApplicationRef#isStable)すると、キャッシュの使用を停止します。 -By default, `HttpClient` caches all `HEAD` and `GET` requests which don't contain `Authorization` or `Proxy-Authorization` headers. You can override those settings by using [`withHttpTransferCacheOptions`](api/platform-browser/withHttpTransferCacheOptions) when providing hydration. +デフォルトでは、`HttpClient` は `Authorization` または `Proxy-Authorization` ヘッダーを含まないすべての `HEAD` および `GET` リクエストをキャッシュします。ハイドレーションを提供する際に [`withHttpTransferCacheOptions`](api/platform-browser/withHttpTransferCacheOptions) を使用して、これらの設定をオーバーライドできます。 ```typescript bootstrapApplication(AppComponent, { @@ -337,11 +337,11 @@ bootstrapApplication(AppComponent, { }); ``` -## Configuring a server +## サーバーの設定 {#configuring-a-server} -### Node.js +### Node.js {#node-js} -The `@angular/ssr/node` extends `@angular/ssr` specifically for Node.js environments. It provides APIs that make it easier to implement server-side rendering within your Node.js application. For a complete list of functions and usage examples, refer to the [`@angular/ssr/node` API reference](api/ssr/node/AngularNodeAppEngine) API reference. +`@angular/ssr/node` は、Node.js環境向けに `@angular/ssr` を拡張したものです。Node.jsアプリケーション内でサーバーサイドレンダリングを実装しやすくするAPIを提供します。関数と使用例の完全なリストについては、[`@angular/ssr/node` APIリファレンス](api/ssr/node/AngularNodeAppEngine) を参照してください。 ```typescript // server.ts @@ -358,21 +358,21 @@ app.use('*', (req, res, next) => { if (response) { writeResponseToNodeResponse(response, res); } else { - next(); // Pass control to the next middleware + next(); // 次のミドルウェアに制御を渡す } }) .catch(next); }); /** - * The request handler used by the Angular CLI (dev-server and during build). + * Angular CLI (開発サーバーおよびビルド時) で使用されるリクエストハンドラー。 */ export const reqHandler = createNodeRequestHandler(app); ``` -### Non-Node.js +### Node.js以外 {#non-node-js} -The `@angular/ssr` provides essential APIs for server-side rendering your Angular application on platforms other than Node.js. It leverages the standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects from the Web API, enabling you to integrate Angular SSR into various server environments. For detailed information and examples, refer to the [`@angular/ssr` API reference](api/ssr/AngularAppEngine). +`@angular/ssr` は、Node.js以外のプラットフォームでAngularアプリケーションをサーバーサイドレンダリングするための重要なAPIを提供します。Web APIの標準的な [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) および [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) オブジェクトを活用することで、さまざまなサーバー環境にAngular SSRを統合できます。詳細情報と例については、[`@angular/ssr` APIリファレンス](api/ssr/AngularAppEngine) を参照してください。 ```typescript // server.ts @@ -381,7 +381,7 @@ import { AngularAppEngine, createRequestHandler } from '@angular/ssr'; const angularApp = new AngularAppEngine(); /** - * This is a request handler used by the Angular CLI (dev-server and during build). + * これは、Angular CLI (開発サーバーおよびビルド時) で使用されるリクエストハンドラーです。 */ export const reqHandler = createRequestHandler(async (req: Request) => { const res: Response|null = await angularApp.render(req);