【发布时间】:2018-11-16 10:56:43
【问题描述】:
我使用 Gatsby 和 Netlify 编写应用程序。
我在 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.development 和 env.production 一切正常。
当我在本地构建和提供应用程序时,我没有问题。我打电话时变量是正确的:
process.env.SNIPCART_API_KEY
在 Netlify 中,我在构建参数中指出了我的生产变量:
SNIPCART_API_KEY = PROD_VALUE
但是当站点正在部署时,该变量不会被考虑在内。 (.env 文件在 .gitignore 中)
我认为我在 Netlify 设置中做错了,但我不知道是什么。
站点部署后如何访问此变量?
【问题讨论】: