如何配置webpack-dev-server代理仅放行/dist/路径请求?
Hey Eric, I’ve run into this exact proxy configuration issue before—let’s get this sorted out for you. The key is to make sure WDS handles /dist/ requests locally while sending everything else to your backend on port 55555. Here are two reliable solutions:
Solution 1: Use Reverse Path Matching with context
This approach uses a negated pattern to target all requests except those starting with /dist/, which keeps the configuration clean and straightforward.
Add this to your webpack config’s devServer section:
const path = require('path'); module.exports = { // ... other webpack config options output: { path: path.resolve(__dirname, 'dist'), // Ensure your build files go here filename: '[name].bundle.js' }, devServer: { port: 9000, static: { directory: path.join(__dirname, 'dist'), // Tell WDS to serve static files from /dist/ }, proxy: { // Match all requests NOT starting with /dist/ '!/dist/**': { target: 'http://localhost:55555', changeOrigin: true, // Critical for avoiding CORS issues with your backend // Add secure: false if your backend uses HTTPS but has a self-signed certificate } } } };
How this works:
- The
!/dist/**pattern tells WDS to skip proxying any request that matches/dist/or its subpaths. - The
staticconfiguration makes WDS serve files directly from your local/dist/directory instead of sending those requests to the backend.
Solution 2: Use bypass with Correct Logic
If you prefer using a root path proxy (/) but need to exclude /dist/, you can fix your bypass function to return the right value. The common mistake here is returning an incorrect response instead of letting WDS handle the static file.
Here’s the corrected bypass setup:
const path = require('path'); module.exports = { // ... other webpack config options output: { path: path.resolve(__dirname, 'dist'), filename: '[name].bundle.js' }, devServer: { port: 9000, static: { directory: path.join(__dirname, 'dist'), }, proxy: { '/': { target: 'http://localhost:55555', changeOrigin: true, bypass: function(req, res, proxyOptions) { // If the request starts with /dist/, let WDS handle it locally if (req.path.startsWith('/dist/')) { return false; // Return false to skip proxying } } } } } };
Why this fixes your connection issue:
- Returning
falsein thebypassfunction tells WDS: "Don’t proxy this request—serve it from the static directory instead." - Previously, if you returned a string or incorrect value, WDS would try to respond with that content instead of serving the static file, causing connection interrupts.
Quick Checks to Verify
- Run your dev server command (like
npm run dev) and test requests:- A request to
http://localhost:9000/dist/main.jsshould load your bundled file directly from WDS. - A request to
http://localhost:9000/api/usersshould be proxied tohttp://localhost:55555/api/users.
- A request to
- Ensure your backend server is running on port 55555 while testing.
内容的提问来源于stack exchange,提问作者Eric

