4

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 :(

1 Answer 1

8

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.