Thủ thuật Website

Cách tạo tuyến đường /sitemap.xml trong khuôn khổ Remix

Theo google.com

Sơ đồ trang web là một tệp nơi bạn cung cấp thông tin về các trang, video và các tệp khác trên trang web của mình và mối quan hệ giữa chúng. Các công cụ tìm kiếm như Google đọc tệp này để thu thập dữ liệu trang web của bạn hiệu quả hơn.

Trước hết, chúng tôi sẽ cần sự trợ giúp của gói rất mạnh mẽ này có tên là Remix SEO . Vì vậy, hãy cài đặt nó bằng cách sử dụng lệnh sau.

npm i @balavishnuvj/remix-seo

Sau đó, tạo một tệp mới có tên sitemapRoutes.server.tstrong ứng dụng / thư mục của chúng tôi. Sau khi tạo tệp, hãy dán đoạn mã sau vào đó.

import type { EntryContext } from "@remix-run/node";
import { generateSitemap } from "@balavishnuvj/remix-seo";

const siteUrl =
  process.env.ENVIRONMENT === "production"
    ? "https://yourProductionWebsiteUrl.com"
    : "http://localhost:3000";

type Handler = (
  request: Request,
  remixContext: EntryContext
) => Promise<Response | null> | null;

export const otherRootRoutes: Record<string, Handler> = {
  "/sitemap.xml": async (request, remixContext) => {
    return generateSitemap(request, remixContext, {
      siteUrl,
    });
  },
};

export const otherRootRouteHandlers: Array<Handler> = [
  ...Object.entries(otherRootRoutes).map(([path, handler]) => {
    return (request: Request, remixContext: EntryContext) => {
      if (new URL(request.url).pathname !== path) return null;

      return handler(request, remixContext);
    };
  }),
];

Đó là nó cho sitemapRoutes.server.tstệp. Bây giờ, hãy truy cập entry.server.tsxtệp trong thư mục / ứng dụng và thực hiện các thay đổi sau ở đó:

import type { EntryContext } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { renderToString } from "react-dom/server";
+ import { otherRootRouteHandlers } from "./sitemapRoutes.server";


- export default function handleRequest(
+ export default async function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  remixContext: EntryContext
) {
+  for (const handler of otherRootRouteHandlers) {
+    const otherRouteResponse = await handler(request, remixContext);
+    if (otherRouteResponse) return otherRouteResponse;
+  }
  const markup = renderToString(
    <RemixServer context={remixContext} url={request.url} />
  );

  responseHeaders.set("Content-Type", "text/html");

  return new Response("<!DOCTYPE html>" + markup, {
    status: responseStatusCode,
    headers: responseHeaders,
  });
}

và bây giờ bạn đã hoàn thành! Xin chúc mừng bạn đã làm được;)
Bây giờ bạn chỉ cần truy cập vào http://localhost:3000/sitemap.xmlliên kết và bạn sẽ thấy sơ đồ trang web được tạo như thế này:

Related Articles

Trả lời

Email của bạn sẽ không được hiển thị công khai.

Back to top button