React exluding files from being cached

时间:2018-09-22 22:49:14

标签: javascript reactjs service-worker

I am developing a project in React and I want to exclude some specific pdf files from being saved in the cache. I am using typical code for service worker provided in create-react-app

export default function register() {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {

      return;
    }

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

      if (isLocalhost) {
        checkValidServiceWorker(swUrl);

        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker'
          );
        });

      } else {
        registerValidSW(swUrl);
      }
    });
  }

I have no idea where should I do it and how.

1 个答案:

答案 0 :(得分:0)

我想我找到了解决方案。不幸的是,它需要在项目上使用eject。之后,我们需要在webpack.config.prod.js文件夹中找到一个名为config的文件。然后搜索SWPrecacheWebpackPlugin。它有一个名为staticFileGlobsIgnorePatterns的参数。在那里我们可以添加我们想要的任何东西。默认值为[/\.map$/, /asset-manifest\.json$/]