You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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.

1. Inject Runtime Variables via the 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:
    1. Open your public/index.html and 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>
      
    2. 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_filter module to dynamically replace values without modifying files:
        location / {
          sub_filter '%SOME_RUNTIME_KEY%' '$your_nginx_env_var';
          sub_filter_once off;
        }
        
    3. In your Vue components or utils, access the variable like this. For cleaner code, wrap it in a utility function:
      // 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';
      };
      
      Then use it in a component:
      import { getRuntimeVar } from '@/utils/runtimeEnv';
      
      export default {
        mounted() {
          console.log('Runtime key:', getRuntimeVar('SOME_RUNTIME_KEY'));
        }
      };
      
2. Load an External Config File (More Flexible for Multiple Vars)

If you have several runtime variables to configure, having a separate JSON file is easier for third parties to manage.

  • Steps to implement:
    1. Create a config.json file in your public directory (this will be copied to the dist folder during build):
      {
        "SOME_RUNTIME_KEY": "default_fallback_value"
      }
      
    2. 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');
        });
      
    3. Third parties only need to edit the dist/config.json file with their specific values—no need to touch HTML or compiled JS. Access the values in components just like the first method.
3. Vue CLI Build-Time Vars (Limitations to Note)

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.
Important Notes
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:59:56