-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (48 loc) · 1.56 KB
/
index.js
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
54
55
56
57
58
59
const Minimatch = require('minimatch').Minimatch
const sm = require('sitemap')
module.exports = function nuxtSitemap (options) {
// Defaults
const defaults = {
path: '/sitemap.xml',
hostname: null,
excludes: [],
routes: []
}
// Combine sources
const sitemap = Object.assign({}, defaults, this.options.sitemap, options)
const nuxt = this.nuxt
let staticRoutes = []
// Extend build
this.extendBuild((config, { isClient, isServer }) => {
if (isClient) {
staticRoutes = nuxt.routes
// Exclude routes
sitemap.excludes.forEach(pattern => {
const minimatch = new Minimatch(pattern)
minimatch.negate = true
staticRoutes = staticRoutes.filter(route => minimatch.match(route))
})
}
})
// Server Middleware
this.addServerMiddleware({
path: sitemap.path,
async handler (req, res) {
let sitemapConfig = {}
// Set sitemap hostname
if (!sitemap.hostname) {
const protocol = req.headers['x-forwarded-proto'] || (req.connection.encrypted ? 'https' : 'http')
sitemapConfig.hostname = `${protocol}://${req.headers.host}/`
} else {
sitemapConfig.hostname = sitemap.hostname
}
// Set sitemap urls
const generateRoutes = await nuxt.utils.promisifyRoute(sitemap.routes)
sitemapConfig.urls = staticRoutes.concat(generateRoutes)
// Create & Stringify sitemap
const sitemapSource = sm.createSitemap(sitemapConfig).toString()
res.setHeader('Content-Type', 'application/xml')
res.end(sitemapSource)
}
})
}