在create-react-app中,如何排除index.html文件不被服务工作者缓存?

15
我有一个使用create-react-app的ReactJs应用程序。该应用程序使用service-worker和其他PWA功能,但是我发现尽管更新网站或部署新版本,Chrome始终从service worker中选择index.html,并且根本不进行网络调用。
我认为使用service worker缓存index.html是问题所在,但一直无法将其排除在缓存之外。我查看了SO上的一些问题和Github上的问题,但无法解决此问题。
我正在使用默认的service-worker注册:
registerServiceWorker.js
// In production, we register a service worker to serve assets from local cache.

// 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 the "N+1" visit to a page, since previously
// cached resources are updated in the background.


// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 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 (/*process.env.NODE_ENV === 'production' &&*/ 'serviceWorker' in navigator) {
       // alert('found' + process.env.NODE_ENV);
        // The URL constructor is available in all browsers that support SW.
        const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
        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('load', () => {
            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);
            } else {
                // Is not local host. Just register service worker
                registerValidSW(swUrl);
            }
        });


    } else {
        //alert('not found' + process.env.NODE_ENV);
    }
}

function registerValidSW(swUrl) {
    navigator.serviceWorker
        .register(swUrl)
        .then(registration => {

            registration.onupdatefound = () => {
                const installingWorker = registration.installing;

                installingWorker.onstatechange = () => {
                    if (installingWorker.state === 'installed') {
                        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('New content is available; please refresh.');
                        } 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.');
                        }
                    }
                };
            };
        })
        .catch(error => {
            console.error('Error during service worker registration:', error);
        });
}

function checkValidServiceWorker(swUrl) {
    // Check if the service worker can be found. If it can't reload the page.
    fetch(swUrl)
        .then(response => {
            // Ensure service worker exists, and that we really are getting a JS file.
            if (
                response.status === 404 ||
                response.headers.get('Content-Type').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);
            }
        })
        .catch(() => {
            console.log(
                'No internet connection found. App is running in offline mode.'
            );
        });
}

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

请帮忙。


请查看此链接:https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker 关于“从缓存中提供文件”的内容,请再次查看。 - Robert Rowntree
1
我认为这篇文章对于直接使用 service worker 会有所帮助。Create-react-app 提供了一个默认配置。因为在我的 service worker 代码中没有看到安装事件,所以我不确定在哪里添加代码来排除 index.html 免受 service worker 的影响。 - Nayan Srivastava
有任何解决方案吗? - VnoitKumar
@VnoitKumar 抱歉,忘记回答了。已添加,请查看。 - Nayan Srivastava
3个回答

4

在尝试多种选项后,效果最佳的一种并不是我真正愿意实施的,但我没有找到更好的。

service-worker.js文件中移除以下行:

workbox.routing.registerNavigationRoute("/index.html", {

  blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/],
});

这将不会缓存index.html,每次都会从服务器上获取,虽然这听起来不是最好的方法,但可以解决问题。

3
如果你已经从create-react-app中退出,你可以进入/config/webpack.config.js并将GenerateSW()的默认参数更改为以下内容:
new WorkboxWebpackPlugin.GenerateSW({
          clientsClaim: true,
          exclude: [/\.map$/, /asset-manifest\.json$/, /index.html/],
          importWorkboxFrom: "cdn",
          navigateFallbackBlacklist: [
            // Exclude URLs starting with /_, as they're likely an API call
            new RegExp("^/_"),
            // Exclude URLs containing a dot, as they're likely a resource in
            // public/ and not a SPA route
            new RegExp("/[^/]+\\.[^/]+$")
          ]

这样,你就不必在每次构建后手动更改 serviceworker.js。

0

针对使用 InjectManifest 而非 GenerateSW 的人

你可能已经发现,blacklistnavigateFallbackBlacklist 选项在 InjectManifest 中不被允许。

我的解决方案是创建一个 index-shell.html 文件,该文件可以被缓存,而将原始的 index.html 文件排除在缓存之外。

new InjectManifest({
   include: [
      /index-shell\.html$/,
   ],
   exclude: [
      /index\.html$/,
   ],
   modifyURLPrefix: {'/public/': '/'}, // solved my routing issues with publicPath and what not...
   ...
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接