React 应用程序:API 密钥保存在返回未定义的 gitignored 文件中
React app: API key kept in gitignored file returning undefined
这真的应该很简单,但我正在开发一个反应网络应用程序,并且在 src 目录外的一个名为 credentials.js 的文件中有一个 google API 键,文件列在 .gitignore.
作为测试,我在 search_bar.js 中导入了 credentials.js 并且只是安慰 API 键只是为了看看我是否能够通过它,但是我得到了"undefined" 作为日志。我尝试了很多在网上找到的建议,但没有成功。我究竟做错了什么?实际密钥在下面编辑。
//appName/credentials.js
(I've tried adding a semi colon at the end)
export const GOOGLE_API_KEY = 'redacted'
//appName/.gitignore
credentials.js
//appName/components/search_bar.js
import React, { Component } from 'react';
import GOOGLE_API_KEY from '../../credentials.js';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
}
render() {
return (
<div>
<input
value={this.state.term}
onChange={event => {console.log(GOOGLE_API_KEY)}}
/>
</div>
);
}
}
export default SearchBar;
您需要对非默认导出使用括号表示法。
尝试:
import { GOOGLE_API_KEY } from '../../credentials.js';
或将导出设置为默认值。
文档:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
这真的应该很简单,但我正在开发一个反应网络应用程序,并且在 src 目录外的一个名为 credentials.js 的文件中有一个 google API 键,文件列在 .gitignore.
作为测试,我在 search_bar.js 中导入了 credentials.js 并且只是安慰 API 键只是为了看看我是否能够通过它,但是我得到了"undefined" 作为日志。我尝试了很多在网上找到的建议,但没有成功。我究竟做错了什么?实际密钥在下面编辑。
//appName/credentials.js
(I've tried adding a semi colon at the end)
export const GOOGLE_API_KEY = 'redacted'
//appName/.gitignore
credentials.js
//appName/components/search_bar.js
import React, { Component } from 'react';
import GOOGLE_API_KEY from '../../credentials.js';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
}
render() {
return (
<div>
<input
value={this.state.term}
onChange={event => {console.log(GOOGLE_API_KEY)}}
/>
</div>
);
}
}
export default SearchBar;
您需要对非默认导出使用括号表示法。
尝试:
import { GOOGLE_API_KEY } from '../../credentials.js';
或将导出设置为默认值。
文档:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export