Created
May 6, 2020 11:36
-
-
Save mrmcc3/e8b0dbe755922afeb9edd8848c01e997 to your computer and use it in GitHub Desktop.
Next.js + Workbox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { generateSW } = require('workbox-build') | |
const { readFileSync } = require('fs') | |
const { map, concat, flatMap, pickBy, uniq } = require('lodash') | |
const buildId = readFileSync('.next/BUILD_ID', 'utf8') | |
const extraPreCachePatterns = [ | |
'public/img/**', | |
'public/favicon.ico', | |
'public/manifest.json' | |
] | |
function readBuildManifest() { | |
const { pages } = JSON.parse( | |
readFileSync('.next/build-manifest.json', 'utf8') | |
) | |
const deps = uniq(flatMap(pages, (v) => v)) | |
return map(deps, (url) => ({ url: `_next/${url}`, revision: null })) | |
} | |
function readPreRenderManifest() { | |
const { routes } = JSON.parse( | |
readFileSync('.next/prerender-manifest.json', 'utf8') | |
) | |
return flatMap(routes, ({ dataRoute }, route) => [ | |
{ url: route, revision: buildId }, | |
{ url: dataRoute.substr(1), revision: null } | |
]) | |
} | |
function isStaticPage(val, key) { | |
return key !== '/404' && val.endsWith('.html') | |
} | |
function readStaticPages() { | |
const pages = JSON.parse( | |
readFileSync('.next/serverless/pages-manifest.json', 'utf8') | |
) | |
return map(pickBy(pages, isStaticPage), (_, url) => ({ | |
url, | |
revision: buildId | |
})) | |
} | |
function uriEncodeEntry({ url, revision }) { | |
return { url: encodeURI(url), revision } | |
} | |
function uriEncodeManifest(manifest) { | |
return { manifest: map(manifest, uriEncodeEntry) } | |
} | |
console.log('[Workbox] generating service worker...') | |
generateSW({ | |
additionalManifestEntries: concat( | |
readBuildManifest(), | |
readPreRenderManifest(), | |
readStaticPages() | |
), | |
manifestTransforms: [uriEncodeManifest], | |
dontCacheBustURLsMatching: /^_next\/static/, | |
inlineWorkboxRuntime: true, | |
offlineGoogleAnalytics: true, | |
globDirectory: '.', | |
globPatterns: [`.next/static/${buildId}/**/*.js`, ...extraPreCachePatterns], | |
swDest: 'public/sw.js', | |
modifyURLPrefix: { | |
'.next/static': '_next/static', | |
public: '' | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment