Tuỳ chỉnh sitemap trong NextJS

Thật ra thì cũng không rành cái này lắm, nhưng ghi lại để lưu trữ kẻo sau này lại quên. Github chính chủ: https://github.com/iamvishnusankar/next-sitemap Mặc định nội dung sitemaps next-sitemap.config.js nó như thế này: Trang này dùng tuy FE nó là NextJS nhưng BE vẫn là WordPress, nên cần loại bỏ cái đám URL của […]

Tuỳ chỉnh sitemap trong NextJS

Thật ra thì cũng không rành cái này lắm, nhưng ghi lại để lưu trữ kẻo sau này lại quên.

Github chính chủ: https://github.com/iamvishnusankar/next-sitemap

Mặc định nội dung sitemaps next-sitemap.config.js nó như thế này:

/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: process.env.SITE_URL || 'https://example.com',
  generateRobotsTxt: true, // (optional)
  // ...other options
}Code language: TypeScript (typescript)

Trang này dùng tuy FE nó là NextJS nhưng BE vẫn là WordPress, nên cần loại bỏ cái đám URL của WordPress, cũng như cái đống route rác của Next.

exclude: [
        '/login/',
        '/preview/',
        '/reset-password/',
        '/sign-up/',
        '/readinglist',
        '/submission',
        '/wp-**/**',
        '/edit/**',
    ],Code language: TypeScript (typescript)

Giờ thì bỏ đi các path /yyyy/mm/dd

if (path.match(/\/\d{4}\/\d{2}\/\d{2}\/.*/gim)) {
        return null
}Code language: TypeScript (typescript)

Và xử lý cái khó chịu nhất, các ký tự / tự thành %2F

const decodedPath = decodeURIComponent(path)Code language: TypeScript (typescript)

Gom lại làm cái transform

    transform: (config, path) => {
        if (path.match(/\/\d{4}\/\d{2}\/\d{2}\/.*/gim)) {
            return null
        }
        const decodedPath = decodeURIComponent(path)
        return {
            loc: decodedPath,
            lastmod: config.autoLastmod ? new Date().toISOString() : undefined,
        }
    },Code language: TypeScript (typescript)

Xong việc nhớ thêm script vào package.json

{
  "build": "next build",
  "postbuild": "next-sitemap"
}Code language: JavaScript (javascript)
A
WRITTEN BY

ArcLight

Responses (0 )