如何在Webpack开发模式及dev-server中停止Workbox构建Service Worker
Got it, I’ve been right where you are—Service Workers are a game-changer for production caching, but they’re such a nuisance in development with stale cache conflicts and unexpected behavior. Here’s a straightforward way to skip building and registering the Service Worker when you’re running in webpack-dev-server or development mode:
Step 1: Conditionally Add the Workbox Plugin
In your Webpack config file, wrap the InjectManifest plugin in an environment check so it only gets included when you’re building for production.
First, import the plugin:
const { InjectManifest } = require('workbox-webpack-plugin');
Then update your plugins array:
module.exports = { // ... rest of your Webpack configuration plugins: [ // Your other plugins (like HtmlWebpackPlugin) go here // Only inject the Service Worker in production mode process.env.NODE_ENV === 'production' && new InjectManifest({ swSrc: './src/service-worker.js', // Path to your custom SW source file swDest: 'service-worker.js', // Add any additional Workbox options you need here }), ].filter(Boolean), // Filter out falsy values to avoid adding undefined plugins in dev mode };
Step 2: Conditionally Register the Service Worker
Even if you skip building the SW, your client-side registration code will throw errors in development if it tries to register a non-existent file. Wrap your registration logic in the same environment check.
In your main app entry file (like src/index.js):
// Only register the Service Worker in production if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { window.addEventListener('load', async () => { try { const registration = await navigator.serviceWorker.register('/service-worker.js'); console.log('Service Worker registered successfully:', registration); } catch (err) { console.error('Service Worker registration failed:', err); } }); }
Step 3: Ensure Environment Variables Are Set Correctly
Make sure your package.json scripts set the proper mode so process.env.NODE_ENV behaves as expected:
{ "scripts": { "dev": "webpack serve --mode development", "build": "webpack --mode production" } }
Bonus: Clean Up Old Service Workers in Development
If you previously registered a Service Worker in development, it might linger and cause issues. Add this optional snippet to unregister old SWs when in dev mode:
if (process.env.NODE_ENV === 'development' && 'serviceWorker' in navigator) { navigator.serviceWorker.getRegistrations().then(registrations => { registrations.forEach(reg => reg.unregister()); }); }
This setup keeps your production build fully functional with Workbox, while wiping out all the dev-mode Service Worker headaches.
内容的提问来源于stack exchange,提问作者Nick Platt

