我无法在netlify中访问我的环境变量

时间:2018-11-16 10:56:43

标签: gatsby netlify

我使用 Gatsby Netlify 编写应用程序。

我正在通过html.js中的环境变量使用 Snipcart 公共API密钥(在开发人员中具有测试密钥,在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设置中做错了,但是我不知道是什么。

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

1 个答案:

答案 0 :(得分:4)

确定研究后,我只需要在变量前加上GATSBY_

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

相关问题