javascriptreactjswebpackcreate-react-appsw-precache

How to configure sw-precache-webpack-plugin to cache custom paths


I have created a react app with create-react-app and ejected it. service-worker.js is looking for /index.html, /static/js/main.js and /static/css/main.css to cache. I want to configure it to look for /index.html, /js/main.js and /js/main.css without changing their output directory. Thanks


Solution

  • The first thing to know is that sw-precache does not actually include your source code. What they do is they generate a list of files that they will retrieve and store in a cache as soon as they are installed.

    That said if you have ejected I would recommend you upgrade to the latest version which is now called Workbox. (https://developers.google.com/web/tools/workbox/get-started/webpack)

    The way I always use it is to have it scan a directory for particular file types and include those. So if I ever add an image to a directory it will be included in the new service-worker. You can have it set to scan your build folder.

    new workboxPlugin({
      globDirectory: path.resolve('build'),
      globPatterns: ['**/*.{html,js,css,png,svg}'],
      swDest: path.resolve('dist', 'sw.js'),
    }),
    

    For other options (such as ignoring large files, not refreshing hashed assets etc you can look at the configuration documentation here: (https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.Configuration)