当我使用 env 文件时,我在读取 vars 时得到了 undefined
When I use env files I got undefined when I read the vars
我使用 vue/cli
创建了一个 Vue 应用程序:vue create my-vue
。我想在 next
模式下构建这个项目(比如 qa
、stage
、next
...),所以我遵循了 steps in the Vue docs。我在根项目中创建了 .env.next
文件,内容如下:
FOO=next
在我的 main.js
中,我将其记录到控制台:
import Vue from 'vue'
import App from './App.vue'
console.log({ f: process.env.FOO }); // <----- undefined. why?
console.log({ f: process.env.VUE_APP_FOO }); // <----- undefined. why?
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
在那之后,我运行构建:
npm run build -- --mode next
当我在控制台中 运行 dist 文件夹 时,我得到 undefined
。我在捆绑包中搜索“下一个”,但没有。
为什么?如何在构建输出中使用 .env
变量?
如您链接的文档中所述:
Note that only NODE_ENV
, BASE_URL
, and variables that start with VUE_APP_
will be statically embedded into the client bundle with webpack.DefinePlugin
. It is to avoid accidentally exposing a private key on the machine that could have the same name.
要在构建输出中使用 FOO
,请在 .env
文件中将其重命名为 VUE_APP_FOO
,并相应地更新引用:
console.log({ f: process.env.VUE_APP_FOO })
我使用 vue/cli
创建了一个 Vue 应用程序:vue create my-vue
。我想在 next
模式下构建这个项目(比如 qa
、stage
、next
...),所以我遵循了 steps in the Vue docs。我在根项目中创建了 .env.next
文件,内容如下:
FOO=next
在我的 main.js
中,我将其记录到控制台:
import Vue from 'vue'
import App from './App.vue'
console.log({ f: process.env.FOO }); // <----- undefined. why?
console.log({ f: process.env.VUE_APP_FOO }); // <----- undefined. why?
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
在那之后,我运行构建:
npm run build -- --mode next
当我在控制台中 运行 dist 文件夹 时,我得到 undefined
。我在捆绑包中搜索“下一个”,但没有。
为什么?如何在构建输出中使用 .env
变量?
如您链接的文档中所述:
Note that only
NODE_ENV
,BASE_URL
, and variables that start withVUE_APP_
will be statically embedded into the client bundle withwebpack.DefinePlugin
. It is to avoid accidentally exposing a private key on the machine that could have the same name.
要在构建输出中使用 FOO
,请在 .env
文件中将其重命名为 VUE_APP_FOO
,并相应地更新引用:
console.log({ f: process.env.VUE_APP_FOO })