在 Github 上让 Netlify 访问被 .gitignore 隐藏的文件

Giving Netlify access to a file hidden by .gitignore on Github

当我尝试在 Netlify 上托管项目时,运行 对 Github 中的存储库感到有点进退两难。该项目包含一个名为 config.js 的文件,并且在两个 HTML 页面上都被引用。它包括一些变量和一个函数来存储我的 Google Maps API 密钥,因此我创建了一个 .gitignore 文件以将其隐藏在我的 Github 存储库中。问题是,既然我已经将它部署在 Netlify 中,我不确定如何将 config.js 引用为环境变量或类似的东西,以便 Netlify 能够找到我的 Google 地图 API 呈现网站时的键。现在,网站呈现了,但它不太好用,因为我 运行 出错了,因为 Netlify 看不到我的 config.js 文件。

你会在下面看到我的文件结构,包括 .gitignore 命令和我的 config.js,它存储 Google Maps API 键以及以下变量和函数调用:

let head = document.getElementsByTagName("head").item(0);
let script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute(
  "src",
  "<MY GOOGLE MAPS API KEY>"
);
head.appendChild(script);

我的问题是,如何在 Netlify 的环境变量中引用上面存储我的 API 密钥的变量?或者,有没有办法只允许 Netlify 访问 config.js 文件而不在 Github 中公开它?

Netlify 上有一些关于部署密钥和子模块的文档,但我不理解文档的那部分内容,我不确定它们是否与我的问题相关。

如前所述,您可以将要包含在静态站点中的变量添加到 Netlify's environment variables。这使它们远离 Git 存储库。

棘手的部分是将这些变量从 Netlify 构建环境中取出并放入您的源代码中。您至少有两种不同的选择,具体取决于变量的敏感程度:

  1. 如果您不希望您的变量被检入 Git 但您可以将它们嵌入到您的 public Javascript/HTML 文件中(Google 地图 API 键可能属于此类),您可以在页面中使用像 to inject environment variables into your source code. If you're using React or another framework, they usually have ways to include environment variables from the build environment. If you aren't, you may just need to write a custom build script or leverage a pre-built NPM package to inject a small <script>var myVar = "<myEnvironmentVariableValue>";</script> into your HTML page on build. Actually it looks like Netlify can inject some custom script 这样的构建工具。也许你可以试试。

  2. 如果您的变量比较敏感并且您不希望它们public公开,您需要添加一个实际的服务器端组件。这可能与无服务器 API 或标准单调的 Web 服务器一样奇特。然后,当您的前端需要这个秘密变量时,它会联系服务器并请求它,大概是从您网站的经过身份验证的部分。这将变量排除在 public HTML/JS 之外,但仍然允许您的站点按需访问它们。