Search code examples
reactjstypescriptgoogle-chromewebpackgoogle-chrome-extension

React Scripts webpack config for background service workers


I am writing a chrome extension in ReactJS and TS that uses a service worker. As per the new manifest V3 requirements I need to specify my service worker like this

"background": {
  "service_worker": "serviceWorker.js"
}

In my /src folder which contains my TS code, serviceWorker.ts is contained within a folder called background-scripts to distinguish it from my normal content scripts.

However, when I build the extension with these changes and unpack the build folder generated by webpack and react-scripts (react-scripts build from CRA) the extension loader cannot find the serviceWorker.js file and fails to load my extension.

This is because the webpack.config.json file obfuscates the names of all of the TS files during build.


The react-scripts webpack config is in /node-modules/react-scripts/config. This file is on the react-scripts GitHub repo.


It appeared I can filter individual files to keep their name

filename: '[name]' === 'serviceWorker' ? 'static/js/[name].js' : isEnvProduction
        ? 'static/js/[name].[contenthash:8].js'
        : isEnvDevelopment && 'static/js/bundle.js'

This is what I have so far. It doesn't work because I believe that '[name]' === 'serviceWorker' will always evaluate to false, but I don't understand how I get the filename property to compare them.


Solution

  • To achieve this you can add custom entries as follows:

    entry: {
      main: paths.appIndexJs,
      serviceWorker: { import: "/path/to/service-worker", filename: "/folder/filename.js"  }
    }
    

    If you get the cannot read 'filter' of undefined error scroll down to line 686 and change the entrypoints.main to whatever you called your main bundle above.

    If you have any questions please leave a comment.