チュートリアル: JSS Next.jsアプリでのビルド時の静的パスのカスタマイズ

Version:
日本語翻訳に関する免責事項

このページの翻訳はAIによって自動的に行われました。可能な限り正確な翻訳を心掛けていますが、原文と異なる表現や解釈が含まれる場合があります。正確で公式な情報については、必ず英語の原文をご参照ください。

多くのページ、製品、または記事を含む非常に大規模なWebサイトでは、すべてのページの静的生成に時間がかかる場合があります。静的生成から一部の種類のページ/アイテムを除外することで、静的に生成されたアプリケーションのビルド時間を短縮できます。

これを実現するには、getStaticPaths関数でカスタマイズされたsitemap-fetcherを使用して、ビルド時に静的に生成されるページ パスの一覧を変更します。

このチュートリアルでは、次の方法について説明します。

  • カスタム サイトマップ サービスを作成します。

  • カスタムサイトマップフェッチャーを作成して、静的パスのリストをカスタマイズします。

カスタム サイトマップ サービスを作成する

クラスGraphQLSitemapServiceとインターフェースGraphQLSitemapServiceConfigを拡張して、特定のアイテムタイプを除外できるようにすることができます。

  1. src/libで、新しいファイルsitemap-service.tsを作成します。

  2. 新しいファイルで、Sitecore Next.js SDKからクラスGraphQLSitemapService IDとインターフェイスGraphQLSitemapServiceConfigをインポートします。

      import {
        GraphQLSitemapService,
        GraphQLSitemapServiceConfig,
      } from '@sitecore-jss/sitecore-jss-nextjs';
  3. GraphQLSitemapServiceConfigを拡張し、サービス設定にオプションを追加します。

      export interface ExtendedSitemapServiceConfig extends GraphQLSitemapServiceConfig {
        /**
        * Item with sub-paths to exclude
        */
    
        excludeItemId?: string;
      }
  4. Sitecore Delivery Edgeでは、検索クエリに有効なIDが必要です。 excludeItemIdオプションを使用しない場合は、有効で空のidを指定する必要があります。 emptyID定数を宣言します。

    const emptyId = '{00000000-0000-0000-0000-000000000000}';
  5. GraphQLSitemapServiceクラスを拡張し、query getterをオーバーライドして、excludeItemIdにIDを指定すると、その型の項目が返されないようにします。

    export class ExtendedSitemapService extends GraphQLSitemapService {
      protected get query(): string {
        return /* GraphQL */ `
          query SitemapQuery(
            $rootItemId: String!
            $language: String!
            $pageSize: Int = 10
            $hasLayout: String = "true"
            $after: String
            $excludeItemId: String = "${this.options.excludeItemId ?? emptyId}"
          ) {
            search(
              where: {
                AND: [
                  { name: "_path", value: $rootItemId, operator: CONTAINS }
                  { name: "_path", value: $excludeItemId, operator: NCONTAINS }
                  { name: "_language", value: $language }
                  { name: "_hasLayout", value: $hasLayout }
                ]
              }
              first: $pageSize
              after: $after
            ) {
              total
              pageInfo {
                endCursor
                hasNext
              }
              results {
                url {
                  path
                }
              }
            }
          }
        `;
      }
      constructor(public options: ExtendedSitemapServiceConfig) {
        super(options);
      }
    メモ

    クエリパラメータ で$excludeItemId: String = "${this.options.excludeItemId ?? emptyId}"を提供し、s earchクエリに{ name: "_path", value: $excludeItemId, operator: NCONTAINS }条件を提供します。

カスタムサイトマップフェッチャーを作成して、静的パスのリストをカスタマイズします

新しいサイトマップ サービスが導入されたことで、ニーズに合ったサイトマップ フェッチャーを追加できるようになりました。

  • src/lib/sitemap-fetcher.jsで、新しいサイトマップ サービスなど、必要なライブラリをインポートします。

    /* eslint-disable @typescript-eslint/no-var-requires */
    import { StaticPath } from '@sitecore-jss/sitecore-jss-nextjs';
    import { GetStaticPathsContext } from 'next';
    import config from 'temp/config';
    import { config as packageConfig } from '../../package.json';
    import { ExtendedSitemapService } from './sitemap-service'; // your new service
    import { ItemIds } from './constants';

リファクタリングされたサイトマップ フェッチャーを使用して、アプリ内の動的ルートの静的パスのリストをカスタマイズできるようになりました。

一部のアイテムタイプを除くすべてのページをフェッチします

新しいExtendedSitemapServiceを使用して、静的パスのリストから特定のアイテムタイプを除外するサイトマップ フェッチャーを作成できます。

たとえば、Products以外のすべてのページを取得するには、次のようにします。

  1. src/lib/sitemap-fetcher.jsで、次のRootSitemapFetcherを実装します。

    export class RootSitemapFetcher {
      private _graphqlSitemapService: ExtendedSitemapService;
    
      constructor() {
        this._graphqlSitemapService = new ExtendedSitemapService({
          endpoint: config.graphQLEndpoint,
          apiKey: config.sitecoreApiKey,
          siteName: config.jssAppName,
          excludeItemId: ItemIds.Products, // Exclude products
        });
      }
    
      async fetch(context?: GetStaticPathsContext): Promise<StaticPath[]> {
        return (process.env.EXPORT_MODE
          ? this._graphqlSitemapService.fetchExportSitemap(packageConfig.language)
          : this._graphqlSitemapService.fetchSSGSitemap(context?.locales || [])
        ).then((results) => {
          // Compensate for current bug on Delivery Edge where the root '/products' item
          // is being returned from the search query which excludes it ({ name: "_path", value: $productsItemId, operator: NCONTAINS })
          return results.filter((value) => value.params.path[0] !== 'products');
        });
      }
    }
  2. RootSitemapFetcherのインスタンスをエクスポートします。

    export const rootSitemapFetcher = new RootSitemapFetcher();
  3. ファイルsrc/pages/...path.tsxで、RootSitemapFetcherのインスタンスをインポートします。

    import { rootSitemapFetcher } from 'lib/sitemap-fetcher';
  4. rootSitemapFetcherを使用するようにgetStaticPathsを変更/追加します。

    export const getStaticPaths: GetStaticPaths = async (context) => {
      if (process.env.NODE_ENV !== 'development') {
        // Note: Next.js runs export in production mode
        const paths = await rootSitemapFetcher.fetch(context);
    
        return {
          paths,
          fallback: process.env.EXPORT_MODE ? false : 'blocking',
        };
      }
    
      return {
        paths: [],
        fallback: 'blocking',
      };
    };

製品のみを取得する

新しいExtendedSitemapServiceを使用して、特定の種類のアイテムのみをフェッチできます。

たとえば、Productsのみを取得するには、次のようにします。

  1. src/lib/sitemap-fetcher.jsでは、製品パスのみを返すProductSitemapFetcherを実装します。

    export class ProductSitemapFetcher {
      private _graphqlSitemapService: ExtendedSitemapService;
    
      constructor() {
        this._graphqlSitemapService = new ExtendedSitemapService({
          endpoint: config.graphQLEndpoint,
          apiKey: config.sitecoreApiKey,
          siteName: config.jssAppName,
          rootItemId: ItemIds.Products, // Only products
        });
      }
    
      async fetch(context?: GetStaticPathsContext): Promise<StaticPath[]> {
        return (process.env.EXPORT_MODE
          ? this._graphqlSitemapService.fetchExportSitemap(packageConfig.language)
          : this._graphqlSitemapService.fetchSSGSitemap(context?.locales || [])
        ).then((results) => {
          results.forEach((value) => {
            value.params.path.shift(); // Remove the leading 'products' path fragment
          });
          return results;
        });
      }
    }
  2. フェッチャーのインスタンスをエクスポートします。

    export const productSitemapFetcher = new ProductSitemapFetcher();
  3. ファイルsrc/pages/products/path.tsxで、ProductSitemapFetcherのインスタンスをインポートします。

    import { productSitemapFetcher } from 'lib/sitemap-fetcher';
  4. productSitemapFetcherを使用するようにgetStaticPaths機能を変更/追加します。

    export const getStaticPaths: GetStaticPaths = async (context) => {
    
      if (process.env.NODE_ENV !== 'development') {
          // Note: Next.js runs export in production mode
          const paths = await productSitemapFetcher.fetch(context);
    
          return {
            paths,
            fallback: process.env.EXPORT_MODE ? false : 'blocking',
          };
        }
    
        return {
          paths: [],
          fallback: 'blocking',
        };
      };
この記事を改善するための提案がある場合は、 お知らせください!