如何在Vue.js运行时读取并配置服务器环境变量?
Great question—this is such a common gotcha when building Vue apps that need to be configurable after you’ve handed off the build artifacts to a third party. Let’s walk through the most practical solutions here, since Vue CLI’s docs can be a bit vague on runtime environment variables.
window Object (Simplest Approach) This is the most straightforward method, and it lets third parties modify values without touching your compiled Vue code.
- Here's how to set it up:
- Open your
public/index.htmland add a script block in the<head>section to define a global placeholder for your env vars:<script> // Global object to hold runtime config window.__APP_RUNTIME_ENV__ = { SOME_RUNTIME_KEY: '%SOME_RUNTIME_KEY%' // Placeholder value }; </script> - After you build your app (using
npm run build), the third party can replace the placeholder with their actual value using server-side tools. For example:- Using a shell script with
envsubst(common in Linux environments):# Replace placeholders with environment variables envsubst < dist/index.html > dist/index.html.tmp && mv dist/index.html.tmp dist/index.html - Using Nginx's
sub_filtermodule to dynamically replace values without modifying files:location / { sub_filter '%SOME_RUNTIME_KEY%' '$your_nginx_env_var'; sub_filter_once off; }
- Using a shell script with
- In your Vue components or utils, access the variable like this. For cleaner code, wrap it in a utility function:
Then use it in a component:// src/utils/runtimeEnv.js export const getRuntimeVar = (key) => { // Fall back to build-time vars if runtime isn't set return window.__APP_RUNTIME_ENV__?.[key] || process.env[key] || 'default_value'; };import { getRuntimeVar } from '@/utils/runtimeEnv'; export default { mounted() { console.log('Runtime key:', getRuntimeVar('SOME_RUNTIME_KEY')); } };
- Open your
If you have several runtime variables to configure, having a separate JSON file is easier for third parties to manage.
- Steps to implement:
- Create a
config.jsonfile in yourpublicdirectory (this will be copied to thedistfolder during build):{ "SOME_RUNTIME_KEY": "default_fallback_value" } - Load this config file before initializing your Vue app (in
main.js):import { createApp } from 'vue'; import App from './App.vue'; // Fetch config before mounting the app fetch('/config.json') .then(response => response.json()) .then(config => { window.__APP_CONFIG__ = config; createApp(App).mount('#app'); }) .catch(error => { console.error('Failed to load runtime config:', error); // Fall back to defaults if config can't be loaded window.__APP_CONFIG__ = { SOME_RUNTIME_KEY: 'default_value' }; createApp(App).mount('#app'); }); - Third parties only need to edit the
dist/config.jsonfile with their specific values—no need to touch HTML or compiled JS. Access the values in components just like the first method.
- Create a
Vue CLI does support environment variables prefixed with VUE_APP_, but these are baked into the code at build time. That means if the third party needs to set a value you couldn't predict during your build, this method won't work unless they're willing to re-run the build themselves.
- If they do want to rebuild, they just need to set the variable before running the build command:
export VUE_APP_SOME_RUNTIME_KEY="their_specific_value" npm run build - Then access it in Vue with
process.env.VUE_APP_SOME_RUNTIME_KEY. But again, this only works if they're comfortable rebuilding the app—so it's not ideal for your use case where the value is unknown at your build time.
- Never store sensitive data in runtime variables: All frontend variables are visible to anyone inspecting the page source, so keep these values non-sensitive (like API endpoints, feature flags, etc.).
- Always set default values: This prevents your app from breaking if the third party forgets to configure a variable.
- Test the flow: Before handing off the app, test modifying the runtime variables yourself to make sure everything works as expected.
内容的提问来源于stack exchange,提问作者Charles Okwuagwu

