Browse Source

added auto sitemap generation to build script

tonyboylehub 1 year ago
parent
commit
052dfec708
2 changed files with 8 additions and 17 deletions
  1. 5 15
      generate-sitemap.mjs
  2. 3 2
      package.json

+ 5 - 15
src/pages/sitemap.xml.js → generate-sitemap.mjs

@@ -1,11 +1,11 @@
 import fs from 'fs'
 import path from 'path'
 
-export async function getServerSideProps({ res }) {
+export async function generateSitemap() {
 
   let directoryPath = path.join(process.cwd(), 'src/pages').replace(/\\/g, '/')
 
-  let files = []
+  let files= []
 
   function throughDirectory(directory) {
     fs.readdirSync(directory).forEach((file) => {
@@ -19,8 +19,6 @@ export async function getServerSideProps({ res }) {
 
   console.log(directoryPath)
 
-  const regex = new RegExp(/directoryPath|.js|.md/, '')
-
   const filter = [
     '/api',
     '_app.jsx',
@@ -65,17 +63,9 @@ export async function getServerSideProps({ res }) {
         .join('')}
     </urlset>`
 
-  // Set the content type to XML
-  res.setHeader('Content-Type', 'text/xml')
-  // Send the XML response
-  res.write(sitemap)
-  res.end()
+  fs.writeFileSync('src/pages/sitemap.xml', sitemap)
+  console.log('Sitemap generated!')
 
-  return {
-    props: {},
-  }
 }
 
-export default function Sitemap() {
-  // The function is empty because the response is handled in getServerSideProps
-}
+generateSitemap()

+ 3 - 2
package.json

@@ -4,9 +4,10 @@
   "private": true,
   "scripts": {
     "dev": "next dev",
-    "build": "next build",
+    "build": "node generate-sitemap.mjs && next build",
     "start": "next start",
-    "lint": "next lint"
+    "lint": "next lint",
+    "sitemap": "node generate-sitemap.js"
   },
   "browserslist": "defaults, not ie <= 11",
   "dependencies": {