mischnic / parcel-plugin-sw-cache Goto Github PK
View Code? Open in Web Editor NEWπ¦π· Parcel plugin for caching using a service worker
Home Page: https://npm.im/parcel-plugin-sw-cache
License: MIT License
π¦π· Parcel plugin for caching using a service worker
Home Page: https://npm.im/parcel-plugin-sw-cache
License: MIT License
Currently the navigatorFallback for the workbox looks like this:
workbox.generateSW(
Object.assign({
globDirectory: outDir,
globPatterns: ['**\/*.{html,js,css,jpg,png}'],
swDest: swDest,
navigateFallback: publicURL + "/index.html",
clientsClaim: true,
skipWaiting: true,
"templatedUrls": {
"/": ["index.html"]
}
This can cause an issue with when the publicURL is equal to "/". The issue is that the generated service worker output sets the the workbox.routing.registerNavigatorRoute to look like this:
workbox.routing.registerNavigationRoute("//index.html");
As a result I have to change the code for the navigateFallback to be like this.
navigateFallback: publicURL + "index.html",
If I don't do this deployment to Firebase fails when the front end routes are reloaded. ideally the registerNavigationRoute should look like this when the service worker is created.
workbox.routing.registerNavigationRoute("/index.html");
The swDest property of the config gets carried over between builds which means when we directly modify swDest from config here, the subsequent rebuild is going to fail since config.swDest
already contains the old resolved path and we are adding additional path config.swDest
.
We end up with something like:
'/pathToYourFile/file/pathToYourFile/file'
We can fix this by changing this line to
config.swDest = path.resolve(outDir, config.swDest);
If I use cache-only, how can I make it expire after lets say 1 hour?
e.g.
new Regexp("regex.sd", "g")
but only for specific properties
How to add other types of files to globPatterns and change the default behavior?
Today the default cofiguration only supports this file types, how to chance and add sounds files like .wav and .mp3
globPatterns: ["**/*.{html,js,css,jpg,png}"],
It worked for me:
config:
"cache": {
"runtimeCaching": [
{
"urlPattern": "http://localhost:1234/cache.jpg",
"handler": "staleWhileRevalidate",
"options": {
"broadcastUpdate": {
"channelName": "api-updates"
}
}
}
]
}
index.js
const updatesChannel = new BroadcastChannel('api-updates');
updatesChannel.addEventListener('message', event => {
console.log(event);
});
index.html contained <img src="http://localhost:1234/cache.jpg">
.
Changing out cache.jpg fires the eventlistener.
Did you use staleWhileRevalidate
?
Originally posted by @mischnic in #4 (comment)
Hi,
me again,
I have this error while using the plugin in inject
mode:
UnhandledPromiseRejectionWarning: Error: No files match the pattern: /Users/me/Documents/project/dist/thaime-service-worker.js
This seems to come from the replace function in the inject Promise chain.
Shouldn't it be:
workbox
.injectManifest(injectOptions)
// return the promise
.then(() =>
replace({
files: config.swDest || swDest,
from: /__PUBLIC/g,
to: publicURL,
})
)
.then(() => printErr('sw-cache: Service worker injection completed.'))
.catch(error =>
printErr('sw-cache: Service worker injection failed: ' + error)
)
If this is really an error, I can come with a PR :)
Is it possible to configure the plugin to load workbox-sw.js from a local source, rather than the Google CDN?
If not, it should be.
Say, the plug-in installs workbox-sw as a npm dependency, and at Parcel build time, it copies the production version of workbox-sw.js from its local node_modules folder, places it in /dist/ and sw.js does only
importScript('workbox-sw.js')
For one of my projects, getting workbox from the Google CDN takes longer than not using a service worker at all.
Thanks.
For inject
strategy, there should be a possibility to overload the default injectionPointRegexp regex that is used to match where to register cached routes.
Reference
Parcel is published as parcel
on npm too. It would be nice to suppress warnings like has unmet peer dependency
by changing the peer dependency from parcel-bundler to just parcel.
This plugin does not work with the latest (at the time of writing) [email protected]
.
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.
I have some imports, as well as some other modern JavaScript features in the ServiceWorker but they are not processed by Parcel/Babel β the generated file still contains:
import {skipWaiting} from 'workbox-core';
import {precacheAndRoute} from 'workbox-routing';
How to make Parcel to process the file?
I am using the following config:
"cache": {
"strategy": "inject",
"swSrc": "./js/selfoss-sw-offline.js",
"templatedURLs": {},
"swDest": "service-worker.js"
}
Hi,
first thank you for this great plugin!
Second, is there a reason that you override some defaults of the generatesw config (skipWaiting
& clientsClaim
)?
I was expecting that the same default configuration was used by your code.
Nothing big though as it can be easily overriden in the package.json
.
But IMO it should stick to the workbox default or at least mention any deviation from it in the README.md :)
In the first case, the update should be made in a major releaseβ¦
In all cases I can make a PR if needed.
Anyway, thanks again for making/maintaining this!
When strategy is set to inject
, swDest variable is not overwritten for link replacement logic, which results in code trying to locate default file. The following exception is thrown:
sw-cache: Service worker injection failed: Error: No files match the pattern: path-to-your-file/sw.js
Suggested fix:
then(() =>
files: swConfig.swDest ? swConfig.swDest : swDest ,
from: /__PUBLIC/g,
to: publicURL,
});
)
Performance scenario:
On a current project getting index.html from Github Pages takes just over 300ms. And from disk cache about 30ms.
But getting it from the service worker takes 800ms+. So I do not want to cache index.html. I have achieved this with the following:
"globDirectory": "./dist", "globPatterns": [ "**\/*.{css,js}" ], "globIgnores": [ "./index.html" ],
However, workbox-sw still creates workbox.routing.registerNavigationRoute("index.html");
in sw.js. And because index.html is not cache, it is not served and the website simply does not work.
I have hacked my way around this by removing that line from sw.js manually -- by adding a sed -i /registerNavigationRoute/d dist/sw.js
at the end of my build script. But this seems inelegant.
Is there a way to tell the plug-in to not do the registerNavigationRoute?
There might be old files in the build dir from previous runs
-> Only add current files to list
If so, how is it implemented in package.json, and how would a page listen to the notification?
Are you planning on porting this to Parcel 2? I would like to try Parcel 2 alpha with selfoss but lack of Service Worker plug-in is felt.
I tried wrapping my head around the new plugin classification for Parcel 2 but do not see how could something like this be done in a single package.
I get an error when I bundle:
Cannot read property 'package' of null
at Bundler.bundler.on.bundle (C:\Users\me\node_modules\parcel-plugin-sw-cache\index.js:30:54)
coming from this line
I tried adding the cache
property to my package.json. but it didn't help.
I'm on Windows 10, the error occurs in PowerShell and WSL Ubuntu Bash
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.