next-js สร้าง site map

ใน NextJs เราสามารถใช้ next-sitemap เพื่อทำการสร้าง sitemap ได้

ก่อนอื่นเราก็ไปติดตั้งกันก่อน

npm install next-sitemap

จากนั้นใน next.config.js ให้เราไปเพิ่ม config sitemap ไว้ตามตัวอย่างด้านล่าง

const SitemapPlugin = require('next-sitemap-plugin').default;

module.exports = {
  plugins: [
    new SitemapPlugin('https://example.com', ['/'])
  ]
}

จากนั้นเราก็ใช้ next build แล้วต่อด้วย next export ได้เลย

ทางเลือกอื่น

ทางเลือกอื่นเราสามารถ config ได้อีกหลายแบบ อีกตัวอย่างหนึ่ง เราจะสร้าง next-sitemap.config.js

จากนั้นก็ config ข้างใน ตัวอย่างเช่น

ตัวอย่างโค้ด

module.exports = {
    siteUrl: process.env.SITE_URL || 'https://devcode.doesystem.com/',
    generateRobotsTxt: true,
}

จากนั้นให้เราไปเพิ่ม script ใน package.json โดยเพิ่ม

"postbuild": "next-sitemap --config next-sitemap.config.js"

script นี้จะรันหลังจาก build จากนั้นเราก็สามารถ build แล้วก็ export ได้เลย

ดูรายละเอียดเพิ่มเติมได้ที่ https://www.npmjs.com/package/next-sitemap-plugin



Copyright © 2023 Devcode Code Example - Powered by www.doesystem.com