我在项目根目录中有 .env 文件,在我的 nuxt 配置中,我使用变量来配置 ReCaptcha,如下所示:
import dotenv from 'dotenv'
dotenv.config()
export default {
modules: [
['@nuxtjs/recaptcha', {
siteKey: process.env.RECAPTCHA_SITE_KEY,
version: 3,
size: 'compact'
}],
]
}
在 .env 中像这样:RECAPTCHA_SITE_KEY=6L....
但应用程序总是因控制台日志错误而失败:ReCaptcha error: No key provided
当我像这样直接硬编码 ReCaptcha key 时:
siteKey: 6L....
应用程序开始工作,所以我想问题在于读取 nuxt.config 中的 .env Prop 你知道如何解决吗?
编辑:
我尝试通过@kissu 推荐和我在这里找到的示例更新我的 nuxt.config:https://www.npmjs.com/package/@nuxtjs/recaptcha
所以有新的 nuxt.config 也不起作用:
export default {
modules: [
'@nuxtjs/recaptcha',
],
publicRuntimeConfig: {
recaptcha: {
siteKey: process.env.RECAPTCHA_SITE_KEY,
version: 3,
size: 'compact'
}
}
}
最佳答案
如果您的 Nuxt 版本是 2.13以上 ,你不要需要使用@nuxtjs/dotenv
或类似的东西,因为它已经被支持到框架中。
要使用某些变量,您需要有一个 .env
项目根目录下的文件。 git应该忽略这个。然后你可以在那里输入一些键,比如
PUBLIC_VARIABLE="https://my-cool-website.com"
PRIVATE_TOKEN="1234qwer"
在您的 nuxt.config.js
,您必须将这些输入到 2 个对象中,具体取决于您的用例,publicRuntimeConfig
或 privateRuntimeConfig
:export default {
publicRuntimeConfig: {
myPublicVariable: process.env.PUBLIC_VARIABLE,
},
privateRuntimeConfig: {
myPrivateToken: process.env.PRIVATE_TOKEN
}
}
差异 : publicRuntimeConfig
基本上可以在任何地方使用,而privateRuntimeConfig
只能在 SSR 期间使用(如果未发送到浏览器, key 只能保持私有(private))。privateRuntimeConfig
的一个流行用例是用于 nuxtServerInit
或在构建过程中(yarn build
或 yarn generate
)使用 headless CMS 的 API 调用填充应用程序。更多信息可以在这篇博文中找到:https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/
.vue
访问它。直接用 this.$config.myPublicVariable
/plugins
访问它同样,使用此语法 export default ({ $axios, $config: { myPublicVariable } }) => {
$axios.defaults.baseURL = myPublicVariable
}
nuxt.config.js
中的任何键文件,直接用process.env.PRIVATE_TOKEN
有时,the syntax may differ a bit ,在这种情况下,请参阅您的 Nuxt 模块文档。// for @nuxtjs/gtm
publicRuntimeConfig: {
gtm: {
id: process.env.GOOGLE_TAG_MANAGER_ID
}
},
PS:如果你使用
target: server
(默认值),您可以yarn build
和 yarn start
将您的应用部署到生产环境。然后,更改您想要的任何环境变量和 yarn start
再次。将不需要重建。因此名称为 RuntimeConfig!Nuxt3 更新
如前所述here ,您可以将以下内容用于 Nuxt3
nuxt.config.js
import { defineNuxtConfig } from 'nuxt3'
export default defineNuxtConfig({
publicRuntimeConfig: {
secret: process.env.SECRET,
}
}
在任何组件中<script setup lang="ts">
const config = useRuntimeConfig()
config.secret
</script>
关于javascript - 如何在 Nuxt 2 或 3 中使用 .env 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67703133/