mischnic / parcel-plugin-sw-cache

📦👷 Parcel plugin for caching using a service worker
https://npm.im/parcel-plugin-sw-cache
MIT License
47 stars 6 forks source link

broken with parcel-bundler 1.10.1 #13

Closed jthegedus closed 5 years ago

jthegedus commented 5 years ago

This plugin does not work with the latest (at the time of writing) parcel-bundler@1.10.1.

If you update the example and use the default sw.js generation strategy parcel fails on parsing the entry index.html file as it now seems to look for files included with navigator.serviceWorker.register('service-worker.js')

jt@ac:~/projects/parcel-plugin-sw-cache/example$ yarn build
yarn run v1.10.1
$ parcel build --out-dir build src/index.html --public-url /
🚨  /home/jt/projects/parcel-plugin-sw-cache/example/src/service-worker.js: ENOENT: no such file or directory, open '/home/jt/projects/parcel-plugin-sw-cache/example/src/service-worker.js'
Error: ENOENT: no such file or directory, open '/home/jt/projects/parcel-plugin-sw-cache/example/src/service-worker.js'
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
jt@ac:~/projects/parcel-plugin-sw-cache/example
$

It seems if a service worker is to be generated from the output build of parcel then the plugin would need to inject the service worker registration code into the entry html.

mischnic commented 5 years ago

Well, a hacky way to make it work:

        if ('serviceWorker' in navigator) {
            const x = 'service-worker.js';
            navigator.serviceWorker.register(x)
                .then(function(registration) {
                    console.log('Registration successful, scope is:', registration.scope);
                })
                .catch(function(error) {
                    console.log('Service worker registration failed, error:', error);
                });
        }

The main issue is that the service worker isn't ready yet when parcel doesn't the bundling, because the sw is created based on the files created during bundling. There is no official way to do this.

I've opened an issue with parcel: https://github.com/parcel-bundler/parcel/issues/2080

jthegedus commented 5 years ago

Cheers for the quick response. Hopefully, there's a better solution when service workers get more complete native support in parcel bundler.