How to configure service workers with create-react-app

24,112

Solution 1

for people who are still struggling on this. please refer https://create-react-app.dev/docs/making-a-progressive-web-app.

enter image description here

service workers are configured in CRA and will handle the caching for you! You just need to change :-

serviceWorker.unregister();

to

serviceWorker.register();

in your src/index.js file;

Also, service workers work on production mode only so make sure to build your application and serve it locally before testing your app for service workers.

npm i http-server -D

then add this to package.json, in your scripts.

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start-sw": "http-server ./build"
}

now run :-

npm run build && npm run start-sw

hope it helps!

Solution 2

First, you have to do some changes in package.json:

Changes in package.json:

{
  "name": "create-react-pwa",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.7.0",
    "sw-precache": "^4.2.2"
  },
  "dependencies": {
    "react": "^15.4.0",
    "react-dom": "^15.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build && sw-precache --config=sw-precache-config.js",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Then create a js file "sw-precache-confi.js" in the root folder of your project:

sw-precache-config.js:

 module.exports = {
    stripPrefix: 'build/',
    staticFileGlobs: [
      'build/*.html',
      'build/manifest.json',
      'build/static/**/!(*map*)'
    ],
    dontCacheBustUrlsMatching: /\.\w{8}\./,
    swFilePath: 'build/service-worker.js'
};

Changes in index.html, Add service worker in index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <!--
      Notice the use of %PUBLIC_URL% in the tag above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.
      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.
      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.
      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('/service-worker.js');
        });
      }
    </script>
  </body>
</html>

After doing all the things run npm install at root of project then npm start.

Further reading: https://github.com/jeffposnick/create-react-pwa#what-additional-changes-might-be-needed

Solution 3

I would recommend this library called cra-append-sw to add custom service workers to CRA.

Most of the details of how to use it are in the npm page, but simply put you just need to install the library (npm i --save cra-append-sw).

Make a few changes to your package.json:

"start": "react-scripts start && cra-append-sw --mode dev ./public/custom-sw-import.js",
"build": "react-scripts build && cra-append-sw --skip-compile ./public/custom-sw-import.js" 

And finally create a file in your public folder called custom-sw-import.js and all of the service worker code you write there will simply be appended to cra's service worker.

I can verify this works since I applied the same principle to make my website www.futurist-invenzium.com which gives a demo of all the features provided by PWA's.

I also found this blogpost to be helpful if you want a more indepth answer : https://medium.freecodecamp.org/how-to-build-a-pwa-with-create-react-app-and-custom-service-workers-376bd1fdc6d3

Share:
24,112
LilSap
Author by

LilSap

Updated on October 17, 2020

Comments

  • LilSap
    LilSap over 3 years

    I am creating a ReactJS app with the create-react-app utility. How could I configure it to use a file that will contain a service worker?

    EDIT: From Javascript side is clear for me, add the registration in my index.js:

    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('./service_workers/sw.js')
      .then(function(registration) {
        // Registration was successful...
      }).catch(function(err) {
        // registration failed ...
      });
    }
    

    Then my configuration in my service worker file (that for me is in service_wokers/sw.js):

    self.addEventListener('install', function(event) {//my code here...});
    self.addEventListener('activate', function(event) {//my code here...});
    self.addEventListener('fetch', function(event) {//my code here...});
    

    When I run this the console shows: ServiceWorker registration failed: DOMException: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

    The file is not there as I am not configuring Webpack to do that. So I am trying to copy the sw.js file with the ouput with:

    test: 
         /\.(js)$/,
         loader: "file?name=[path][name].[ext]&context=./service_workers",
         include: '/service_worker'
    

    I think there is no need to say that I am totally new to Webpack.