You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需eject,如何在Create React App中排除Service Worker作用域内的URL?

How to Exclude URLs from Service Worker Scope in Create React App Without Ejecting

Hey there! I totally get it—ejecting from Create React App can feel like a risky move that locks you out of future CRA updates, so wanting to tweak your auto-generated service worker’s scope without taking that step makes perfect sense. Let’s walk through two reliable, no-eject approaches to get this done:

Using react-app-rewired

This tool lets you override CRA’s webpack config under the hood without ejecting. Here’s how to set it up:

  • First, install the required packages:
    npm install react-app-rewired workbox-webpack-plugin --save-dev
    
  • Create a config-overrides.js file in your project root with this code:
    const { InjectManifest } = require('workbox-webpack-plugin');
    
    module.exports = function override(config, env) {
      // Remove CRA's default auto-generated service worker plugin
      const workboxPluginIndex = config.plugins.findIndex(
        plugin => plugin.constructor.name === 'GenerateSW'
      );
      if (workboxPluginIndex !== -1) {
        config.plugins.splice(workboxPluginIndex, 1);
      }
    
      // Add a custom service worker setup with excluded URLs
      config.plugins.push(
        new InjectManifest({
          swSrc: './src/service-worker.js', // You'll create this file next
          exclude: [/^\/api\//, /\.html$/], // Add your target excluded patterns here
          // Keep CRA's default service worker behaviors
          clientsClaim: true,
          skipWaiting: true,
        })
      );
    
      return config;
    };
    
  • Create a basic src/service-worker.js file (you can extend this later with custom logic):
    import { precacheAndRoute } from 'workbox-precaching';
    
    // Precache all CRA-generated assets (same as the default SW)
    precacheAndRoute(self.__WB_MANIFEST);
    
    // Add any extra service worker logic here if needed
    
  • Update your package.json scripts to use react-app-rewired instead of react-scripts:
    "scripts": {
      "start": "react-app-rewired start",
      "build": "react-app-rewired build",
      "test": "react-app-rewired test",
      "eject": "react-scripts eject"
    }
    

Using craco (Create React App Configuration Override)

Craco is another popular tool for customizing CRA configs without ejecting, with a cleaner setup for some folks:

  • Install dependencies first:
    npm install @craco/craco workbox-webpack-plugin --save-dev
    
  • Create a craco.config.js file in your project root:
    const { InjectManifest } = require('workbox-webpack-plugin');
    
    module.exports = {
      webpack: {
        configure: (config) => {
          // Remove the default auto-generated service worker plugin
          config.plugins = config.plugins.filter(
            plugin => plugin.constructor.name !== 'GenerateSW'
          );
    
          // Inject our custom service worker with excluded paths
          config.plugins.push(
            new InjectManifest({
              swSrc: './src/service-worker.js',
              exclude: [/^\/api\//, /admin\/.*$/], // Adjust these regex patterns to match your needs
              clientsClaim: true,
              skipWaiting: true,
            })
          );
    
          return config;
        },
      },
    };
    
  • Reuse the same src/service-worker.js file from the previous method.
  • Update your package.json scripts to use craco:
    "scripts": {
      "start": "craco start",
      "build": "craco build",
      "test": "craco test",
      "eject": "react-scripts eject"
    }
    

Quick Tips

  • The exclude array uses regex patterns to target URLs you don’t want the service worker to handle. Tweak these to match your specific routes (like API endpoints, admin dashboards, or static files).
  • By switching from GenerateSW (CRA’s default plugin) to InjectManifest, you keep all the benefits of Workbox’s precaching while gaining full control over which URLs the service worker ignores.
  • Always test your production build after making these changes to confirm the service worker behaves as expected.

内容的提问来源于stack exchange,提问作者Jahil Khalfe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:40:54