I'm using webpack dev server to build a single page application. There are many routes like /api, /alpha, /bravo ... /zulu, and they all need to be proxied.
I wrote webpack.config.js file to proxy all URLs.
proxy: {
"/api": "http://localhost:3000",
"/alpha": {
target: "http://localhost:8080",
pathRewrite: { "^/alpha": "" }
},
"/bravo": {
target: "http://localhost:8080",
pathRewrite: { "^/bravo": "" }
},
"/charlie": {
target: "http://localhost:8080",
pathRewrite: { "^/charlie": "" }
},
...
"/zulu": {
target: "http://localhost:8080",
pathRewrite: { "^/zulu": "" }
},
}
It works well, but I had to write too many codes. I wonder is there any way to reduce it? I thought webpack supports a regular expression for this problem, but I couldn't get a solution from the official docs :(
Webpack dev server's proxy settings are a spin off of the https://github.com/chimurai/http-proxy-middleware#http-proxy-middleware-options.
Documentation says you can use a function on the rewrite prop to do some complex regex work. This, coupled with the ability to define multiple proxy entries and context entries, I would suggest something along the lines of:
proxy: [{
"/api": "http://localhost:3000",
},{
context: ['/alpha', '/bravo', '/charlie', '/zulu'],
target: 'http://localhost:8080',
rewrite: function (path, req) { return path.replace(/\/(.*?)/g, '') }
}]
This reduces your growing list down to a single array.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With