Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment independent builds using the Vue webpack template

I use a build server to build my Vue projects, using the npm run build command nicely supplied by the Vue 2 template. The Vue template also provides the ability to access environment-specific data that can be configured in files underneath the config directory. Things like prod.env.js, etc. You then access this data through process.env.API_PREFIX as seen in the template manual.

I want to be able to build the code once, then deploy the same build (as defined by the output in Dist) to multiple servers, but have the different servers use different configuration (different API_PREFIX etc). Currently, the process.env references are expanded at build time by the Webpack compiler. Therefore I have to rebuild for every environment.

I can think of a few ways to do this -- obviously the loading of the config has to happen at runtime, and given that it runs in the browser and has to refer to some file, it would have to be through an AJAX request for some static JSON configuration served by the web server separately, or similar. But I'd be interested to know how anyone here would handle this requirement.

like image 832
amoe Avatar asked Feb 17 '17 17:02

amoe


People also ask

Does Vue need Webpack?

Vue CLI is built on top of Webpack and so for beginners, you do not need to know what Webpack is as the Vue CLI has taken care of the configurations with great default presets and you literally need 0 configs to start.

How do I get environment variables in Vue 3?

You can access environment variables (with the VITE_ prefix) from your Vue app via the import. meta. env object. For example const myVar = import.


1 Answers

Without knowing your specific architecture is hard to give specific advice. Instead I will leave a few general ideas.

In order to do what you want in a sane way, you probably would have to derive the prefix from the domain in which you are serving the frontend.

There are a few things you can use for that, besides using window.location at runtime:

  • Relative paths /api/myinformation - the prefix will be automatically derived from the domain where the frontend is served at.
  • Local proxy during development, since you might not want to run the backend on localhost https://github.com/vuejs-templates/webpack/blob/master/docs/proxy.md
  • Proxy path rewrite on nginx or similar: https://stackoverflow.com/a/3017720/1445812

Even if it doesn't solve your specific case, hope it gives you an idea of what available.

like image 58
aristidesfl Avatar answered Sep 28 '22 05:09

aristidesfl