当前位置: 首页 > 知识库问答 >
问题:

从create-react-app中的Service Worker缓存中排除index.html

戚飞雨
2023-03-14

我有一个使用CreateReact应用程序的reactJs应用程序。该应用程序使用了service worker和其他PWA功能,但不知何故,我发现尽管更新了网站或部署了新版本,chrome总是选择索引。来自服务人员的html,根本不进行网络呼叫。

我认为使用Service Worker缓存index.html是个问题,但无法将其排除在缓存之外,我确实检查了SO上的一些问题和github上的问题,但无法解决这个问题。

我使用默认的服务工作者注册

注册服务Worker.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();
        });
    }
}

请帮忙。

共有2个答案

姜玮
2023-03-14

如果您已从CreateReact应用程序弹出,则可以进入/config/webpack。配置。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。在每栋楼后面。

傅朝
2023-03-14

在尝试了多个选项后,效果最好的一个不是我真的愿意实施,但找不到更好的。

来自服务人员。js删除以下行中的文件

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

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

这不会缓存index.html,并尝试每次从服务器上拉取它,尽管这听起来不是最好的,但确实有用。

 类似资料:
  • Create React App 不用配置就可以创建 React App。 全局安装: npm install -g create-react-app 创建 App: create-react-app my-appcd my-app/ 启动 npm: npm start 打开 http://localhost:3000/  查看你的 App。 如果你准备将其部署到生产环境,只需创建一个压缩包,并且运行 npm run build。

  • Create React Native App The fastest way to create universal React Native apps npx create-react-native-app Once you're up and running with Create React Native App, visit this tutorial for more informat

  • Create React Redux App Structure Create React + Redux app structure with build configurations. What can I find here? Express, Cors React + Redux, ES6, async/await Web Components (Custom Elements) inte

  • create-react-app React Project with Node Express Backend Example on using create-react-app with a Node Express Backend Usage Install nodemon globally npm i nodemon -g Install server and client depende

  • 问题内容: 我认为这与直接使用webpack有关,因此具有更大的灵活性。但是我不确定是否有人可以解释“退出”的含义。另外,弹出一个create react应用程序会有哪些后果?这样做不好吗? 问题答案: 要引导项目,您将需要了解 Webpack 或 Babel之类的内容 ,这对于不想了解这些内容的人可能是一个症结所在。 提供具有合理默认值(并且可以扩展)的完全配置的环境。大多数与基础架构相关的工作

  • 我正在使用一个快速后端创建反应应用程序。我在端口3001上运行后端,在开发模式下,前端通过端口3000运行。我的package.json中有< code > " proxy ":" http://localhost:3001 " ,api工作得很好。 然而,当我使用yarn build,然后运行< code>serve -s build时,根本就没有进行api调用。我不知道为什么它在生产中不工作,