Avoid a race between reading from and writing to the importScripts
array
#352
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When
WorkboxPlugin.GenerateSW
is called it reads from theimportScripts
array. Webpack instance called from build-custom-worker.js appends to that array via thesuccess
callback. There is no guarantee that webpack compilation will finish beforeGenerateSW
is called. This results in a bug where sometimes no scripts will be imported in the Service Worker code.From my experiments to replicate this issue you need to ensure the webpack compilation is delayed enough. Then
GenerateSW
will not pick up anyimportScripts
. For an example project triggering this bug see: https://github.com/errendir/next-pwa/tree/import-scripts-race-demo/examples/custom-workerAfter running
yarn build
, please open thepublic/sw.js
and format it with Prettier. You will find that no scripts have been imported into the ServiceWorker generated by workbox:The above example works by feeding a very large function into Webpack during custom worker compilation. This slows it down enough so that the race condition can be highlighted.
This PR fixes this issue by appending the name of the custom worker script to the
importScripts
synchronously beforeGenerateSW
is called. Note that this may be before the file is generated, but AFAIKGenerateSW
doesn't verify if the script exists so the problem is solved