在运行时将环境变量传递到Vue App中

docker Vue.js

伽罗前端

2020-03-12

如何在Vue中访问在运行时而不是在构建过程中传递到容器的环境变量?

堆栈如下:

  • VueCLI 3.0.5
  • 码头工人
  • Kubernetes

在stackoverflow和其他地方提出了建议的解决方案,以使用.env文件传递变量(并使用模式),但这是在构建时进行的,并被烘焙到docker映像中。

我想在运行时将变量传递给Vue,如下所示:

  • 创建Kubernetes ConfigMap(我正确了)
  • 运行部署yaml文件时,将ConfigMap值传递到K8s pod env变量中(我正确了)
  • 从上面创建的env变量读取,例如。VUE_APP_MyURL并在我的Vue App中使用该值执行某项操作(我不正确)

我在helloworld.vue中尝试了以下方法:

<template>
<div>{{displayURL}}
  <p>Hello World</p>
</div>
</template>
<script>
export default {  
        data(){
            return{
                displayURL:""
        }
    },
    mounted(){
        console.log("check 1")
        this.displayURL=process.env.VUE_APP_ENV_MyURL
        console.log(process.env.VUE_APP_ENV_MyURL)
        console.log("check 3")
     }
}
</script>

我在控制台日志中返回“未定义”,helloworld页面上没有任何显示。

I've also tried passing the value into a vue.config file and reading it from there. Same "undefined" result in console.log

<template>
<div>{{displayURL}}
  <p>Hello World</p>
</div>
</template>
<script>
const vueconfig = require('../../vue.config');
export default {  
        data(){
            return{
                displayURL:""
        }
    },
    mounted(){
        console.log("check 1")
        this.displayURL=vueconfig.VUE_APP_MyURL
        console.log(vueconfig.VUE_APP_MyURL)
        console.log("check 3")
     }
}
</script>

With vue.config looking like this:

module.exports = {
    VUE_APP_MyURL: process.env.VUE_APP_ENV_MyURL
}

If I hardcode a value into VUE_APP_MyURL in the vue.config file it shows successfully on the helloworld page.

VUE_APP_ENV_MyURL is successfully populated with the correct value when I interrogate it: kubectl describe pod

process.env.VUE_APP_MyURL doesn't seem to successfully retrieve the value.

For what it is worth... I am able to use process.env.VUE_APP_3rdURL successfully to pass values into a Node.js app at runtime.

第1315篇《在运行时将环境变量传递到Vue App中》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
樱阿飞 2020.03.12

我在当前项目中遇到了同样的问题,发现目前无法在运行时访问环境变量,因此我最终得到了创建.env文件或本地环境变量的解决方案,正如您所说的那样在构建时。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android