如何在 Nuxt 插件中访问 .env 变量? [英] How to access .env variables in a Nuxt plugin?
问题描述
Segment Analytics 提供了一个代码段,其中包含一个秘密的 API 密钥.在我的 Nuxt.js
项目中,我创建了一个名为 segment.js
的插件,我在我的 nuxt.config.js
中注册了它:
Segment Analytics provides a snippet with a secret API key in it. In my Nuxt.js
project I created a plugin called segment.js
which I registered in my nuxt.config.js
:
nuxt.config.js
plugins: [
{
src: "~/plugins/segment.js",
mode: 'client'
}
]
在我的 plugins/segment.js
文件中,我有我的代码段:
In my plugins/segment.js
file I have my snippet:
!function(){var analytics=window.analytics=...analytics.SNIPPET_VERSION="4.13.2";
analytics.load(process.env.SEGMENT_API_SECRET);
analytics.page();
}}();
显然我不想在那里暴露我的秘密 API 密钥,所以我将它存储在我的 .env
文件中:
Obviously I don't want to have my secret API key exposed there so I have it stored in my .env
file instead:
.env
SEGMENT_API_SECRET=FR4....GSDF3S
问题:plugins/segment.js
中的 process.env.SEGMENT_API_SECRET
是 undefined
,因此代码段不起作用.如何从我的插件 plugins/segment.js
访问我的 .env
变量 SEGMENT_API_SECRET
?
Problem: process.env.SEGMENT_API_SECRET
in plugins/segment.js
is undefined
so the snippet doesn't work. How can I access my .env
variable SEGMENT_API_SECRET
from my plugin plugins/segment.js
?
推荐答案
将你的 env 变量设置为 nuxt.config.js
Set your env variable into nuxt.config.js
export default {
publicRuntimeConfig: {
segmentApiSecret: process.env.SEGMENT_API_SECRET,
}
}
然后,这个应该可以解决问题
And then, this one should do the trick
// segment.js
export default ({ $config: { segmentApiSecret } }) => {
!function(){var analytics=window.analytics=...analytics.SNIPPET_VERSION="4.13.2";
analytics.load(segmentApiSecret);
analytics.page();
}}();
}
这篇关于如何在 Nuxt 插件中访问 .env 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!