liuderchi / sw-precache-cra

πŸ‘· Customize your service worker in create react app without `npm run eject`

Home Page:https://sw-precache-cra-demo-cra-contributors.netlify.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

sw-precache-cra

πŸ‘· Customize your service worker in create react app without npm run eject

The Problem

Create-react-app provides built-in service-worker.js but when you want to extend it
(e.g. to cache REST API response) you need to do npm run eject and maintain more configs.

Sometimes we just want to enjoy customization but keep those big configs unchanged.
This cli tool helps you achieve this with ease.

Demo

https://sw-precache-cra-demo-cra-contributors.netlify.com/

A page caching GitHub API response with one simple config. Done in 4 steps

Extend Service Worker in Create React App in 2 steps

  1. $ npm i -S sw-precache-cra

  2. Edit the build script in package.json

There are 2 examples:

πŸ’‘ If you want your service worker cache API response with url /messages:

concat the build script

"scripts": {
  "start": "react-scripts start",
- "build": "react-scripts build",
+ "build": "react-scripts build && sw-precache-cra --config sw-config.js",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}

with one additional js module having any sw-precache configs:

// sw-config.js
module.exports = {
  runtimeCaching: [
    {
      urlPattern: '/messages',
      handler: 'networkFirst',
    },
  ],
};

πŸŽ‰ You've got custom build/service-worker.js after npm run build


πŸ’‘ If you want to have Non minified build/service-workder.js you can do this:

"scripts": {
  "start": "react-scripts start",
- "build": "react-scripts build",
+ "build": "react-scripts build && sw-precache-cra --no-minify",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}

πŸŽ‰ You've got Un-minified build/service-worker.js after npm run build

Other API

$ sw-precache-cra --list-config

# Print current config for sw-precache
# If you do not specify a config file, default config by CRA is printed
#
{ swFilePath: './build/service-worker.js',
  cacheId: 'sw-precache-webpack-plugin',
  dontCacheBustUrlsMatching: /\.\w{8}\./,
  navigateFallback: '/index.html',
  navigateFallbackWhitelist: [ /^(?!\/__).*/ ],
  staticFileGlobsIgnorePatterns: [ /\.map$/, /asset-manifest\.json$/ ],
  staticFileGlobs:
   [ './build/**/**.html',
     './build/static/js/*.js',
     './build/static/css/*.css',
     './build/static/media/**' ],
  stripPrefix: './build' }

For more APIs please do sw-precache-cra --help

Reference

License

MIT License

About

πŸ‘· Customize your service worker in create react app without `npm run eject`

https://sw-precache-cra-demo-cra-contributors.netlify.com/

License:MIT License


Languages

Language:JavaScript 100.0%