Adding a ServiceWorker to a Webpack project to enable Offline Caching

Things move so fast in the JavaScript world so please make sure this article is relevant to you.

  • It’s currently March 2018
  • I’m using WebPack 4.2.0

I used offline-plugin to accomplish adding a ServiceWorker to my JavaScript app that uses Webpack as a build tool. The README on the offline-plugin repository page has excellent instructions for setting up this Webpack Plugin.

The code has been reproduced below in gists.

Install

I used version 4.9.0 at the time of writing.

yarn add offline-plugin

or

npm install offline-plugin

Setup

1 – Add offline-plugin to your Webpack config file:

2 – Then, add the runtime into your entry file (typically main entry):

3 – Configure as your project requires.

Service Workers can generally only own files that are located under the location of the ServiceWorker script unless explicitly specified by both Client and Server – see here.

This means you will generally host your Service Worker script at the root level of your site e.g. https://myawesomeapp.com/service-worker.js. This allows the Service Worker to cache all files on your site.

Using the offline-plugin configuration options you can tell the plugin to output the generated Service Worker at the root level of our project. I highly recommend you also set minify to false to prevent conflicts with existing minifiers that may be running.

Notes

You can learn about Service Workers here: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
And you can read the W3C spec here: https://www.w3.org/TR/2017/WD-service-workers-1-20171102/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.