1

Building a MEVN application.

When running in my development environment, there are two servers running concurrently: webpack-dev-server at localhost:8080 serving up the Vue/Webpack-based front-end client application, and localhost:8081 serving the Node+Express back-end application which provides the RESTful endpoints that the client consumes.

When deploying for production, however, the Node+Express server, in addition to providing those endpoints, also serves the static Vue/Webpack application as described in this answer.

My issue is this: To call one of those endpoints from the client in the production environment, since they're all coming from the same server, I can just load /route/to/my/endpoint?param=val or similar. In the dev environment, since they're two separate servers, I'd load http://localhost:8081/route/to/my/endpoint?param=val instead.

It seems like there must be some trivial way to include the http://localhost:8081 in the code when running the webpack-dev-server, but omit it when building for deployment.

I've seen a few articles talking about the publicPath webpack config item, but none of them are quite addressing this issue in a way that makes sense to me.

What's the "right way" to do this?

DanM
  • 7,037
  • 11
  • 51
  • 86

1 Answers1

1

Figured it out a bit more quickly than I expected to.

An easy way to do this is with Webpack's definePlugin mechanism, which is nicely described here.

Essentially, in the plugins section of my webpack.dev.conf.js I added this:

new webpack.DefinePlugin({
  __API__: "'http://localhost:8081'"
}),

and in the same section of webpack.prod.conf.js I added this:

new webpack.DefinePlugin({
  __API__: "''"
}),

Then, in a vue file, when I wanted to hit an endpoint, the call would look like this:

axios.get(__API__ + '/myendpoint')

Critical thing that's mentioned in the above article but easy to miss: The webpack engine does exact text replacement of the identifier, in this case, __API__, and since my code there is expecting a string, it must be defined in the DefinePlugin so it's got quotes around it. An alternate way to do this would be __API__: JSON.stringify("http://localhost:8081") or similar.

DanM
  • 7,037
  • 11
  • 51
  • 86