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.
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.
You can access environment variables (with the VITE_ prefix) from your Vue app via the import. meta. env object. For example const myVar = import.
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:
/api/myinformation
- the prefix will be automatically derived from the domain where the frontend is served at.Even if it doesn't solve your specific case, hope it gives you an idea of what available.
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