【问题标题】:I can not access my environment variables in netlify我无法在 netlify 中访问我的环境变量
【发布时间】:2018-11-16 10:56:43
【问题描述】:

我使用 GatsbyNetlify 编写应用程序。

我在 html.js 中通过环境变量使用 Snipcart 公共 API 密钥(在 dev 中有测试密钥,在 prod 中有实时密钥)。

import React from 'react'
import PropTypes from 'prop-types'

export default class HTML extends React.Component {
  render() {
    return (
      <html lang='en' {...this.props.htmlAttributes}>
        <head>
          <meta charSet='utf-8' />
          <meta httpEquiv='x-ua-compatible' content='ie=edge' />
          <meta
            name='viewport'
            content='width=device-width, initial-scale=1, shrink-to-fit=no'
          />
          {this.props.headComponents}

          {/* Snipcart */}
          <script
            defer
            src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js'
          />
          <script
            defer
            src='https://cdn.snipcart.com/scripts/2.0/snipcart.js'
            id='snipcart'
            data-api-key={process.env.SNIPCART_API_KEY}
          />
          <link
            href='https://cdn.snipcart.com/themes/2.0/base/snipcart.min.css'
            type='text/css'
            rel='stylesheet'
          />
        </head>
        <body {...this.props.bodyAttributes}>
          {this.props.preBodyComponents}
          <div
            key={'body'}
            id='___gatsby'
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}
        </body>
      </html>
    )
  }
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array
}

在本地,我的 .env.developmentenv.production 一切正常。

当我在本地构建和提供应用程序时,我没有问题。我打电话时变量是正确的:

process.env.SNIPCART_API_KEY

在 Netlify 中,我在构建参数中指出了我的生产变量:

SNIPCART_API_KEY = PROD_VALUE

但是当站点正在部署时,该变量不会被考虑在内。 (.env 文件在 .gitignore 中)

我认为我在 Netlify 设置中做错了,但我不知道是什么。

站点部署后如何访问此变量?

【问题讨论】:

    标签: gatsby netlify


    【解决方案1】:

    好的,经过一些研究,我只需在变量前加上GATSBY_

    文档中的更多内容:https://www.gatsbyjs.org/docs/environment-variables/#client-side-javascript

    【讨论】:

    • 记住:不要将任何私有密钥存储到这些客户端变量中。 :)
    • 是的,谢谢 ;) Snipcart API 密钥是公开的,没问题!我直接在 Netlify UI 中设置私钥 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2014-02-11
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多