Skip to content

Commit

Permalink
Fix precache server js issue and workbox register url
Browse files Browse the repository at this point in the history
  • Loading branch information
shadowwalker committed Apr 5, 2022
1 parent 9a92589 commit c6ea26f
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 33 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ yarn-error.log

examples/**/yarn.lock
examples/**/package-lock.json
examples/**/pnpm-lock.yaml
9 changes: 8 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# CHANGELOG

## 5.4.7

### Fix

1. (the real) Fix for not precache server js
2. Fix service worker register url edge case

## 5.4.6

### Fix
Expand Down Expand Up @@ -287,4 +294,4 @@
### Misc

- Add CHANGELOG.md
- Add LICENSE and CHANGELOG.md to .npmignore
- Add LICENSE and CHANGELOG.md to .npmignore
40 changes: 25 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ module.exports = (nextConfig = {}) => ({
webpack,
buildId,
dev,
config: { distDir = '.next', pwa = {}, pageExtensions = ['tsx', 'ts', 'jsx', 'js', 'mdx'], experimental = {}}
config: { distDir = '.next', pwa = {}, pageExtensions = ['tsx', 'ts', 'jsx', 'js', 'mdx'], experimental = {} }
} = options

let basePath = options.config.basePath
Expand Down Expand Up @@ -49,7 +49,7 @@ module.exports = (nextConfig = {}) => ({
reloadOnOnline = true,
scope = basePath,
customWorkerDir = 'worker',
subdomainPrefix, // deprecated, use basePath in next.config.js instead
subdomainPrefix, // deprecated, use basePath in next.config.js instead
...workbox
} = pwa

Expand All @@ -63,7 +63,9 @@ module.exports = (nextConfig = {}) => ({
}

if (subdomainPrefix) {
console.error('> [PWA] subdomainPrefix is deprecated, use basePath in next.config.js instead: https://nextjs.org/docs/api-reference/next.config.js/basepath')
console.error(
'> [PWA] subdomainPrefix is deprecated, use basePath in next.config.js instead: https://nextjs.org/docs/api-reference/next.config.js/basepath'
)
}

console.log(`> [PWA] Compile ${options.isServer ? 'server' : 'client (static)'}`)
Expand Down Expand Up @@ -102,14 +104,16 @@ module.exports = (nextConfig = {}) => ({
customWorkerDir,
destdir: _dest,
plugins: config.plugins.filter(plugin => plugin instanceof webpack.DefinePlugin),
success: ({name}) => importScripts.unshift(name),
success: ({ name }) => importScripts.unshift(name),
minify: !dev
})

if (register) {
console.log(`> [PWA] Auto register service worker with: ${path.resolve(registerJs)}`)
} else {
console.log(`> [PWA] Auto register service worker is disabled, please call following code in componentDidMount callback or useEffect hook`)
console.log(
`> [PWA] Auto register service worker is disabled, please call following code in componentDidMount callback or useEffect hook`
)
console.log(`> [PWA] window.workbox.register()`)
}

Expand All @@ -131,7 +135,8 @@ module.exports = (nextConfig = {}) => ({
// precache files in public folder
let manifestEntries = additionalManifestEntries
if (!Array.isArray(manifestEntries)) {
manifestEntries = globby.sync(
manifestEntries = globby
.sync(
[
'**/*',
'!workbox-*.js',
Expand Down Expand Up @@ -173,7 +178,7 @@ module.exports = (nextConfig = {}) => ({
fallbacks,
basedir: options.dir,
destdir: _dest,
success: ({name, precaches}) => {
success: ({ name, precaches }) => {
importScripts.unshift(name)
precaches.forEach(route => {
if (!manifestEntries.find(entry => entry.url.startsWith(route))) {
Expand All @@ -196,7 +201,10 @@ module.exports = (nextConfig = {}) => ({
exclude: [
...buildExcludes,
({ asset, compilation }) => {
if (asset.name.match(/^(build-manifest\.json|react-loadable-manifest\.json|server\/middleware-manifest\.json|server\/middleware-runtime\.js|_middleware\.js|server\/pages\/_middleware\.js)$/)) {
if (
asset.name.startsWith('server/') ||
asset.name.match(/^(build-manifest\.json|react-loadable-manifest\.json)$/)
) {
return true
}
if (dev && !asset.name.startsWith('static/runtime/')) {
Expand Down Expand Up @@ -266,14 +274,16 @@ module.exports = (nextConfig = {}) => ({
handler: 'NetworkFirst',
options: {
cacheName: 'start-url',
plugins: [{
cacheWillUpdate: async ({request, response, event, state}) => {
if (response && response.type === 'opaqueredirect') {
return new Response(response.body, {status: 200, statusText: 'OK', headers: response.headers});
plugins: [
{
cacheWillUpdate: async ({ request, response, event, state }) => {
if (response && response.type === 'opaqueredirect') {
return new Response(response.body, { status: 200, statusText: 'OK', headers: response.headers })
}
return response
}
return response;
}
}]
]
}
})
}
Expand All @@ -284,7 +294,7 @@ module.exports = (nextConfig = {}) => ({
if (Array.isArray(c.options.plugins) && c.options.plugins.find(p => 'handlerDidError' in p)) return
if (!c.options.plugins) c.options.plugins = []
c.options.plugins.push({
handlerDidError: async ({request}) => self.fallback(request)
handlerDidError: async ({ request }) => self.fallback(request)
})
})
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "next-pwa",
"version": "5.4.6",
"version": "5.4.7",
"description": "Next.js with PWA, powered by workbox.",
"main": "index.js",
"repository": "https://github.com/shadowwalker/next-pwa",
Expand Down
34 changes: 18 additions & 16 deletions register.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,23 @@ import { Workbox } from 'workbox-window'

if (typeof window !== 'undefined' && 'serviceWorker' in navigator && typeof caches !== 'undefined') {
if (__PWA_START_URL__) {
caches.has('start-url').then(function(has) {
caches.has('start-url').then(function (has) {
if (!has) {
caches.open('start-url').then(c => c.put(__PWA_START_URL__, new Response('', {status: 200})))
caches.open('start-url').then(c => c.put(__PWA_START_URL__, new Response('', { status: 200 })))
}
})
}

window.workbox = new Workbox(__PWA_SW__, { scope: __PWA_SCOPE__ })
window.workbox = new Workbox(window.location.origin + __PWA_SW__, { scope: __PWA_SCOPE__ })

if (__PWA_START_URL__) {
window.workbox.addEventListener('installed', async ({isUpdate}) => {
window.workbox.addEventListener('installed', async ({ isUpdate }) => {
if (!isUpdate) {
const cache = await caches.open('start-url')
const response = await fetch(__PWA_START_URL__)
let _response = response
if (response.redirected) {
_response = new Response(response.body, {status: 200, statusText: 'OK', headers: response.headers})
_response = new Response(response.body, { status: 200, statusText: 'OK', headers: response.headers })
}

await cache.put(__PWA_START_URL__, _response)
Expand All @@ -27,28 +27,30 @@ if (typeof window !== 'undefined' && 'serviceWorker' in navigator && typeof cach
}

window.workbox.addEventListener('installed', async () => {
const data = window.performance.getEntriesByType('resource').map(e => e.name).filter(n => n.startsWith(`${window.location.origin}/_next/data/`) && n.endsWith('.json'))
const cache = await caches.open('next-data')
data.forEach(d => cache.add(d))
}
)
const data = window.performance
.getEntriesByType('resource')
.map(e => e.name)
.filter(n => n.startsWith(`${window.location.origin}/_next/data/`) && n.endsWith('.json'))
const cache = await caches.open('next-data')
data.forEach(d => cache.add(d))
})

if(__PWA_ENABLE_REGISTER__) {
if (__PWA_ENABLE_REGISTER__) {
window.workbox.register()
}

if(__PWA_CACHE_ON_FRONT_END_NAV__ || __PWA_START_URL__) {
const cacheOnFrontEndNav = function(url) {
if (__PWA_CACHE_ON_FRONT_END_NAV__ || __PWA_START_URL__) {
const cacheOnFrontEndNav = function (url) {
if (!window.navigator.onLine) return
if (__PWA_CACHE_ON_FRONT_END_NAV__ && url !== __PWA_START_URL__) {
return caches.open('others').then(cache =>
cache.match(url, {ignoreSearch: true}).then(res => {
cache.match(url, { ignoreSearch: true }).then(res => {
if (!res) return cache.add(url)
return Promise.resolve()
})
)
} else if (__PWA_START_URL__ && url === __PWA_START_URL__) {
return fetch(__PWA_START_URL__).then(function(response) {
return fetch(__PWA_START_URL__).then(function (response) {
if (!response.redirected) {
return caches.open('start-url').then(cache => cache.put(__PWA_START_URL__, response))
}
Expand All @@ -74,7 +76,7 @@ if (typeof window !== 'undefined' && 'serviceWorker' in navigator && typeof cach
})
}

if(__PWA_RELOAD_ON_ONLINE__) {
if (__PWA_RELOAD_ON_ONLINE__) {
window.addEventListener('online', () => {
location.reload()
})
Expand Down

0 comments on commit c6ea26f

Please sign in to comment.