From 7eccd146cc6ad32d0f676af315c8b01387ec777b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Albert=20S=C5=82awi=C5=84ski?= Date: Sat, 30 Apr 2022 18:34:05 +0200 Subject: [PATCH] Avoid the race between WorkboxPlugin.GenerateSW reading 'importScripts' and webpack appending to that array --- build-custom-worker.js | 15 ++++++++++----- index.js | 7 +++++-- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/build-custom-worker.js b/build-custom-worker.js index ad383d34..ca187444 100644 --- a/build-custom-worker.js +++ b/build-custom-worker.js @@ -6,7 +6,7 @@ const webpack = require('webpack') const { CleanWebpackPlugin } = require('clean-webpack-plugin') const TerserPlugin = require('terser-webpack-plugin') -const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, success, minify }) => { +const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, minify }) => { let workerDir = undefined if (fs.existsSync(path.join(basedir, customWorkerDir))) { @@ -15,14 +15,19 @@ const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, suc workerDir = path.join(basedir, 'src', customWorkerDir) } - if (!workerDir) return + if (!workerDir) return null const name = `worker-${id}.js` const customWorkerEntries = ['ts', 'js'] .map(ext => path.join(workerDir, `index.${ext}`)) .filter(entry => fs.existsSync(entry)) - if (customWorkerEntries.length !== 1) return + if (customWorkerEntries.length === 0) return null + + if (customWorkerEntries.length > 1) { + console.warn(`> [PWA] WARNING: More than one custom worker found (${customWorkerEntries.join(",")}), not building a custom worker`) + return null + } const customWorkerEntry = customWorkerEntries[0] console.log(`> [PWA] Custom worker found: ${customWorkerEntry}`) @@ -102,10 +107,10 @@ const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, suc console.error(`> [PWA] Failed to build custom worker`) console.error(status.toString({ colors: true })) process.exit(-1) - } else { - success({ name }) } }) + + return name } module.exports = buildCustomWorker diff --git a/index.js b/index.js index 110bcd25..6a396d29 100644 --- a/index.js +++ b/index.js @@ -99,16 +99,19 @@ module.exports = (nextConfig = {}) => ({ if (!options.isServer) { const _dest = path.join(options.dir, dest) - buildCustomWorker({ + const customWorkerScriptName = buildCustomWorker({ id: buildId, basedir: options.dir, customWorkerDir, destdir: _dest, plugins: config.plugins.filter(plugin => plugin instanceof webpack.DefinePlugin), - success: ({ name }) => importScripts.unshift(name), minify: !dev }) + if (customWorkerScriptName !== null) { + importScripts.unshift(customWorkerScriptName) + } + if (register) { console.log(`> [PWA] Auto register service worker with: ${path.resolve(registerJs)}`) } else {