Giter Club home page Giter Club logo

parcel-plugin-sw-cache's Introduction

Parcel plugin for sw-caching

A Parcel plugin to run workbox-build after every build.

yarn add -D parcel-plugin-sw-cache
# or
npm install -D parcel-plugin-sw-cache

The plugin is configured using the cache object inside package.json of your project. (Example). Configuration keys used by the plugin (default options first):

{
    "dependencies": {
        // ...
    },
    //...
    "cache": {
        "disablePlugin": false || true,
        "inDev": false || true,
        "strategy": "default" || "inject"
        "clearDist": true || false
    }
    //...
}

The remaining properties in this object will be passed to generateSW or injectManifest (depending on strategy). See https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build

In inject mode, occurences of __PUBLIC will be replaced with Parcel's public-url option. In this case, swSrc is also a required parameter.

No configuration options are mandatory, the default configuration will work just fine. (Creating a service worker to precache all files in the output directory without runtime caching). With strategy: "default", the default parameters passed to workbox-build are (which precaching all html, js, css, jpg and png files):

{
    globDirectory: outDir,
    globPatterns: ["**/*.{html,js,css,jpg,png}"],
    swDest: swDest,
    navigateFallback: publicURL + "/index.html",
    clientsClaim: true,
    skipWaiting: true,
    templatedURLs: {
        "/": ["index.html"]
    }
}

and with inject:

{
    globDirectory: outDir,
    globPatterns: [
        "**/*.{html,js,css,jpg,png,gif,svg,eot,ttf,woff,woff2}"
    ],
    swDest: swDest,
    templatedURLs: {
        "/": ["index.html"]
    }
}

To specify a RegExp, use an array instead (ignoreURLParametersMatching, navigateFallbackWhitelist, runtimeCaching.urlPattern, injectionPointRegexp).

runtimeCaching: [
    {
        urlPattern: /my-match\/api\.[0-9]+/i
    }
]

becomes

"runtimeCaching": [
    {
        "urlPattern": ["my-match\/api\\.[0-9]+", "i"]
    }
]

parcel-plugin-sw-cache's People

Contributors

dsych avatar hiswe avatar likr avatar mischnic avatar supertopoz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

parcel-plugin-sw-cache's Issues

Parcel 2 support

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.

How to pre-process the service worker with Parcel?

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"
  }

Local source for workboxSW

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.

Cannot read property 'package' of null

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

Add other file types in globPatterns

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}"],

broken with parcel-bundler 1.10.1

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.

swDest does not respect swDest from config.

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,
    });
)

workbox-build needs to be upgraded

Actually workbox-build version 3.6.1 have been installed, but the current version is 4.3.1.

Because of that, some workbox-build dependencies are showing warnings of deprecation.

image

Caching too many files

There might be old files in the build dir from previous runs

-> Only add current files to list

  1. get asset list from bundler
  2. pass to workbox (how?)

generateSW skipWaiting & clientsClaim

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!

Inject Error – `No files match the pattern` for replace-in-file

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 :)

Not caching index.html

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?

Unable to resolve path for swDest.

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);

Broken w/ parcel-bundler 1.11.0

With just the defaults here is the following build output.

image

image

The src file is missing from the service worker.

image

This occurs regardless of whether I use the defaults or inject my own service worker.

publicURL issue when using SPA in Firebase.

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");

Thx. It worked for me: But just chrome, not fireFox, Don't know why

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.