繁体   English   中英

在 Gatsby 中传递环境变量

[英]Passing Environment Variables in Gatsby

我已经查看了这个解释执行以下操作:

注意:由于 Gatsby 使用 Webpack DefinePlugin 使环境变量在运行时可用,因此无法从process.env解构它们。 相反,它们必须被完全引用。

GATSBY_API_URL将作为process.env.GATSBY_API_URL提供给您的站点(客户端和服务器端)。

我目前有这个

useEffect(() => {
    var getRouteConfig = {
      method: 'get',
      url: `https://www.strava.com/api/v3/routes/${props.data.contentfulRoutes.slug}`,
      headers: {
        Authorization: `Bearer ${process.env.GATSBY_STRAVA_BEARER}`,
      },
    };

    axios(getRouteConfig)
      .then((res) => {

在我的.env文件中使用GATSBY_STRAVA_BEARER=2xxx 连同其他变量。 我可以在gatsby-config.js中很好地访问我似乎无法让它们在我的组件中呈现。

如果我要记录process.env.GATSBY_STRAVA_BEARER我得到未定义

我只有require('dotenv').config(); 虽然在我的gatsby-config.js文件的顶部。

试试看。 https://www.gatsbyjs.com/plugins/gatsby-plugin-env-variables/

我在我们自己的项目中使用它,它使访问环境变量在运行时可用。 安装后,在 gatsby-config 中声明这个插件。

// gatsby-config.js
 module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-env-variables`,
      options: {
        allowList: ["APP_URL", "API_URL"]
      },
     },
   ],
 }
 
 // something component
 const Component = () => <div>{process.env.APP_URL}</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM