Search code examples
javascriptwebpackservice-workerworkbox-webpack-plugin

Service Worker endpoints not being found


I have just setup service workers for my project. My webpack.config.js looks as follows...

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const WorkboxPlugin = require('workbox-webpack-plugin');

module.exports = {
  entry: {
    app: './src/index.js',
    worker: './src/worker.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.ProgressPlugin(),
    new HtmlWebpackPlugin({
      title: 'PWA'
    }),
    new WorkboxPlugin.GenerateSW({
      swDest: 'sw.js',
      clientsClaim: true,
      skipWaiting: true,
    }),
    new webpack.HotModuleReplacementPlugin()
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devServer: {
    contentBase: './dist',
    hot: true
  }
};

And my package.json is setup as so...

"scripts": {
  "start": "webpack-dev-server --config ./webpack.config.js --mode development",
  "test": "echo \"Error: no test specified\" && exit 1",
  "build": "webpack"
},

I am able to successfully register the workers by adding the following code to my index.js file...

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').then(registration => {
      console.log('SW registered: ', registration);
    }).catch(registrationError => {
      console.log('SW registration failed: ', registrationError);
    });
  });
}

However, now I do not know where to define my endpoints. I want to define the following code somewhere in my app but I have no idea how ensure that the endpoint is called...

self.addEventListener('fetch', function(event) {
  console.log("Caught a fetch!");
  event.respondWith(new Response("Hello world!"));
});

If I run npm build the sw.js file gets generated in my dist folder, so I tried adding the endpoint there. But when I run npm start afterwards, that endpoint never gets called and the file also disappears (I'm guessing it is getting bundled somewhere). Can someone explain to me what I am doing wrong? Where do I need to define my endpoints and how can I call them?


Solution

  • I was able to get it working by changing the webpack.config.js to use InjectManifest...

    new WorkboxPlugin.InjectManifest({
      swSrc: "./src/src-sw.js",
      swDest: "sw.js"
    })
    

    So now in the src-sw.js I added the following...

    self.addEventListener("install", event => {
      console.log("Installed");
    });
    

    And I was able to get the log in the console.