-
Notifications
You must be signed in to change notification settings - Fork 6
/
sitemap.ts
53 lines (47 loc) · 1.67 KB
/
sitemap.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { mkdirSync, writeFileSync } from 'fs'
import { Readable } from 'stream'
import { dirname } from 'path'
import { SitemapStream, streamToPromise } from 'sitemap'
import { defineNuxtModule, createResolver } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'sitemap',
version: '0.0.1',
configKey: 'sitemap',
compatibility: { nuxt: '^3.0.0-rc.11' },
},
defaults: {
hostname: 'http://localhost:3000',
},
async setup(options, nuxt) {
async function generateSitemap(routes) {
const sitemapRoutes = routes.map(route => route.path)
// https://github.com/ekalinin/sitemap.js#generate-a-one-time-sitemap-from-a-list-of-urls
const stream = new SitemapStream({ hostname: options.hostname })
return streamToPromise(Readable.from(sitemapRoutes).pipe(stream)).then(data =>
data.toString()
)
}
function createSitemapFile(sitemap, filepath) {
const dirPath = dirname(filepath)
mkdirSync(dirPath, { recursive: true })
writeFileSync(filepath, sitemap)
}
const resolver = createResolver(import.meta.url)
const filePath = resolver.resolve(
nuxt.options.srcDir,
'node_modules/.cache/.sitemap/sitemap.xml'
)
nuxt.options.nitro.publicAssets = nuxt.options.nitro.publicAssets || []
nuxt.options.nitro.publicAssets.push({
baseURL: '/',
dir: dirname(filePath),
})
nuxt.hook('pages:extend', async pages => {
const sitemap = await generateSitemap(pages)
createSitemapFile(sitemap, filePath)
// Added output to confirm that the sitemap has been created at the end of the build process
console.log('Sitemap created')
})
},
})