Skip to content

Commit

Permalink
feat: feat: add gzip compression to sitemap by default
Browse files Browse the repository at this point in the history
fixed #16
  • Loading branch information
Nicolas Pennec committed Apr 16, 2018
1 parent e18dbbb commit 6cee9bd
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Expand Up @@ -26,6 +26,7 @@ Module based on the awesome [sitemap](https://github.com/ekalinin/sitemap.js) pa
path: '/sitemap.xml',
hostname: 'https://example.com',
cacheTime: 1000 * 60 * 15,
gzip: true,
generate: false, // Enable me when using nuxt generate
exclude: [
'/secret',
Expand Down Expand Up @@ -77,6 +78,11 @@ Defines how frequently should sitemap **routes** being updated.
This option is only effective when `generate` is `false`.
Please note that after each invalidation, `routes` will be evaluated again. (See [routes](#routes-1) section)

### `gzip`
- Default: `true`

Enable the creation of the `.xml.gz` sitemap compressed with gzip.

## Routes

Dynamic routes are ignored by the sitemap module.
Expand Down
32 changes: 30 additions & 2 deletions src/index.js
Expand Up @@ -16,7 +16,8 @@ const defaults = {
generate: false,
exclude: [],
routes: [],
cacheTime: 1000 * 60 * 15
cacheTime: 1000 * 60 * 15,
gzip: true
}

module.exports = function module (moduleOptions) {
Expand All @@ -28,8 +29,12 @@ module.exports = function module (moduleOptions) {
// sitemap.xml is written to static dir on generate mode
const xmlGeneratePath = path.resolve(this.options.srcDir, path.join('static', options.path))

options.pathGzip = (options.gzip) ? `${options.path}.gz` : options.path
const gzipGeneratePath = path.resolve(this.options.srcDir, path.join('static', options.pathGzip))

// Ensure no generated file exists
fs.removeSync(xmlGeneratePath)
fs.removeSync(gzipGeneratePath)

let staticRoutes = fs.readJsonSync(jsonStaticRoutesPath, { throws: false })
let cache = null
Expand Down Expand Up @@ -75,13 +80,36 @@ module.exports = function module (moduleOptions) {
const routes = await cache.get('routes')
const sitemap = await createSitemap(options, routes)
const xml = await sitemap.toXML()
await fs.ensureFile(xmlGeneratePath)
await fs.writeFile(xmlGeneratePath, xml)
if (options.gzip) {
const gzip = await sitemap.toGzip()
await fs.writeFile(gzipGeneratePath, gzip)
}
})()
}
}
})

// Add server middleware
if (options.gzip) {
// Add server middleware for sitemap.xml.gz
this.addServerMiddleware({
path: options.pathGzip,
handler (req, res, next) {
cache.get('routes')
.then(routes => createSitemap(options, routes, req))
.then(sitemap => sitemap.toGzip())
.then(gzip => {
res.setHeader('Content-Type', 'gzip')
res.end(gzip)
}).catch(err => {
next(err)
})
}
})
}

// Add server middleware for sitemap.xml
this.addServerMiddleware({
path: options.path,
handler (req, res, next) {
Expand Down

0 comments on commit 6cee9bd

Please sign in to comment.