title: Uncaught ReferenceError: process is not defined error when converting react (TS) app to PWA with webpack and babel config
body: <p>I have created a react (TS) using babel + webpack. It is working fine. Now I am converting it to a PWA. I followed this <a href="https://webpack.js.org/guides/progressive-web-application/" rel="nofollow noreferrer">webpack</a> article to updated webpack.config.js. To register the service worker, instead of doing it in index.html, I created a service-worker.tsx and referencing it in index.tsx.</p>
  <p>I am getting this error</p>
  <blockquote>
  <p>service-worker.ts:22 Uncaught ReferenceError: process is not defined
  at register (service-worker.ts:22:33)
  at eval (index.tsx:14:60)
  at ./src/index.tsx (main.js:219:1)
  at <strong>webpack_require</strong> (main.js:253:41)
  at main.js:322:37
  at main.js:324:12</p>
  </blockquote>
  <p>I have added 3 files, where I changed the configuration to integrate workbox, for registering and un registering.</p>
  <p><strong>webpack.config.js</strong></p>
  <pre><code>const HtmlWebPackPlugin = require(&quot;html-webpack-plugin&quot;);
  const WorkboxPlugin = require(&quot;workbox-webpack-plugin&quot;);
  const path = require(&quot;path&quot;);
  
  // const htmlPlugin = new HtmlWebPackPlugin({
  //   template: &quot;./src/index.html&quot;,
  //   filename: &quot;./index.html&quot;,
  // });
  
  const htmlWebPackPlugin =  new HtmlWebPackPlugin({
    title: &quot;PWA Webpack Demo&quot;,
    template: &quot;./src/index.html&quot;,
    filename: &quot;./index.html&quot;,  
  });
  
  const workBoxPlugin_Generate = new WorkboxPlugin.GenerateSW({
    // these options encourage the ServiceWorkers to get in there fast
    // and not allow any straggling &quot;old&quot; SWs to hang around
    clientsClaim: true,
    skipWaiting: true,
  });
  
  module.exports = {
    entry: &quot;./src/index.tsx&quot;,
    resolve: {
      extensions: [&quot;.ts&quot;, &quot;.tsx&quot;, &quot;.js&quot;],
    },
    output: {
      // NEW
      path: path.join(__dirname, &quot;dist&quot;),
      filename: &quot;[name].js&quot;,
    }, // NEW Ends
    plugins: [htmlWebPackPlugin, workBoxPlugin_Generate],
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: &quot;babel-loader&quot;,
          },
        },
        {
          test: /\.(ts|tsx)$/,
          exclude: /node_modules/,
          use: [&quot;ts-loader&quot;],
        },
        // css rules
        {
          test: /\.css$/,
          use: [&quot;style-loader&quot;, &quot;css-loader&quot;],
        },
      ],
    },
  };
  </code></pre>
  <p><strong>service-worker.tsx</strong> (error at export default function register)</p>
  <pre><code>const isLocalhost = Boolean(
      window.location.hostname === &quot;localhost&quot; ||
        // [::1] is the IPv6 localhost address.
        window.location.hostname === &quot;[::1]&quot; ||
        // 127.0.0.1/8 is considered localhost for IPv4.
        window.location.hostname.match(
          /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
        ),
    );
    
    export default function register() {
      if (&quot;serviceWorker&quot; in navigator) {
        // The URL constructor is available in all browsers that support SW.
        const publicUrl = new URL(
          process.env.PUBLIC_URL!,
          window.location.toString(),
        );
        if (publicUrl.origin !== window.location.origin) {
          // Our service worker won't work if PUBLIC_URL is on a different origin
          // from what our page is served on. This might happen if a CDN is used to
          // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
          return;
        }
    
        window.addEventListener(&quot;load&quot;, () =&gt; {
          const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
    
          if (isLocalhost) {
            // This is running on localhost. Lets check if a service worker still exists or not.
            checkValidServiceWorker(swUrl);
    
            // Add some additional logging to localhost, pointing developers to the
            // service worker/PWA documentation.
            navigator.serviceWorker.ready.then(() =&gt; {
              console.log(
                &quot;This web app is being served cache-first by a service &quot; +
                  &quot;worker.&quot;,
              );
            });
          } else {
            // Is not local host. Just register service worker
            registerValidSW(swUrl);
          }
        });
      }
    }
    
    function registerValidSW(swUrl: string) {
      navigator.serviceWorker
        .register(swUrl)
        .then(registration =&gt; {
          registration.onupdatefound = () =&gt; {
            const installingWorker = registration.installing;
            if (installingWorker) {
              installingWorker.onstatechange = () =&gt; {
                if (installingWorker.state === &quot;installed&quot;) {
                  if (navigator.serviceWorker.controller) {
                    // At this point, the old content will have been purged and
                    // the fresh content will have been added to the cache.
                    // It's the perfect time to display a 'New content is
                    // available; please refresh.' message in your web app.
                    console.log(&quot;New content is available; please refresh.&quot;);
                  } else {
                    // At this point, everything has been precached.
                    // It's the perfect time to display a
                    // 'Content is cached for offline use.' message.
                    console.log(&quot;Content is cached for offline use.&quot;);
                  }
                }
              };
            }
          };
        })
        .catch(error =&gt; {
          console.error(&quot;Error during service worker registration:&quot;, error);
        });
    }
    
    function checkValidServiceWorker(swUrl: string) {
      // Check if the service worker can be found. If it can't reload the page.
      fetch(swUrl)
        .then(response =&gt; {
          // Ensure service worker exists, and that we really are getting a JS file.
          if (
            response.status === 404 ||
            response.headers.get(&quot;content-type&quot;)!.indexOf(&quot;javascript&quot;) === -1
          ) {
            // No service worker found. Probably a different app. Reload the page.
            navigator.serviceWorker.ready.then(registration =&gt; {
              registration.unregister().then(() =&gt; {
                window.location.reload();
              });
            });
          } else {
            // Service worker found. Proceed as normal.
            registerValidSW(swUrl);
          }
        })
        .catch(() =&gt; {
          console.log(
            &quot;No internet connection found. App is running in offline mode.&quot;,
          );
        });
    }
    
    export function unregister() {
      if (&quot;serviceWorker&quot; in navigator) {
        navigator.serviceWorker.ready.then(registration =&gt; {
          registration.unregister();
        });
      }
    }
  </code></pre>
  <p><strong>index.tsx</strong></p>
  <pre><code>import { createRoot } from 'react-dom/client';
  import App from &quot;./app&quot;;
  //import * as serviceWorker from './serviceWorker';
  import registerServiceWorker from './service-worker'
  
  const container = document.getElementById('root')!
  const root = createRoot(container)
  root.render(&lt;App /&gt;)
  console.log('Registering service worker', 'Starting...')
  
  registerServiceWorker()
  </code></pre>