React Service Worker:未捕获的语法错误:意外的令牌“<”

问题描述

我正在使用 CRA 创建的 React 应用程序自定义我的 Service Worker。

我所做的唯一更改是创建一个函数来轮询实时更新。所以,我的文件看起来像这样:

// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production,and gives
// it offline capabilities. However,it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page,after all the
// existing tabs open on the page have been closed,since prevIoUsly cached
// resources are updated in the background.

// To learn more about the benefits of this model and instructions on how to
// opt-in,read https://cra.link/PWA

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.0/8 are considered localhost for IPv4.
    window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);

const POLLING_LOOP_MS = 30000;

type Config = {
  onSuccess?: (registration: ServiceWorkerRegistration) => void;
  onUpdate?: (registration: ServiceWorkerRegistration) => void;
};

export function register(config?: Config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL,window.location.href);
    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/facebook/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load',() => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl,config);

        // Add some additional logging to localhost,pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more,visit https://cra.link/PWA'
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl,config)
      }
    });
  }
}

function registerValidSW(swUrl: string,config?: Config) {
  navigator.serviceWorker
    .register(swUrl)
    .then((registration) => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }

        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } 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('Content is cached for offline use.');

              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };

      pollLiveSWUpdates(registration);
    })
    .catch((error) => {
      console.error('Error during service worker registration:',error);
    });
}

function checkValidServiceWorker(swUrl: string,config?: Config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl,{
    headers: { 'Service-Worker': 'script' },})
    .then((response) => {
      // Ensure service worker exists,and that we really are getting a JS file.
      const contentType = response.headers.get('content-type');
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf('javascript') === -1)
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then((registration) => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl,config);
      }
    })
    .catch(() => {
      console.log('No internet connection found. App is running in offline mode.');
    });
}

function pollLiveSWUpdates(registration: ServiceWorkerRegistration) {
  setInterval(async () => {
    await registration.update();
  },POLLING_LOOP_MS);
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready
      .then((registration) => {
        registration.unregister();
      })
      .catch((error) => {
        console.error(error.message);
      });
  }
}

因此,当有新更新时,我会触发 onUpdate 以在应用程序中显示祝酒词。当我点击 toast 中的 Update 按钮时,我跳过等待状态并刷新页面,因此新的服务工作已注册并运行。这样就可以正常工作了。

但是,如果发现新的更新并且我只是刷新页面而不使用我的 toast 跳过当前的等待,我会收到以下错误

Uncaught SyntaxError: Unexpected token '<'

似乎当前的 service worker 正在尝试获取不再可用的缓存块 js 文件。该文件的响应是我的 index.html 的 HTML。我的标头有一些 CSP 和缓存控制策略,但我已删除所有这些策略,错误仍然存​​在。

有时同一情况下的错误是不同的:

Refused to execute script from 'http://localhost:5001/static/js/[DASH].chunk.js' because its MIME type ('text/html') is not executable,and strict MIME type checking is enabled.

如果我尝试使用内置的 serviceWorkerRegistration.ts 文件,也会发生同样的事情。

在这里遗漏了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)