为 Netlify 中的构建设置环境变量 [英] Set environment variable for build in Netlify

查看:84
本文介绍了为 Netlify 中的构建设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的代码中不需要的 API 密钥设置环境变量.我的源 javascript 看起来像这样:

I'm trying to set an environment variable for an API key that I don't want in my code. My source javascript looks something like this :

.get(`http://api-url-and-parameters&api-key=${process.env.API_KEY}`)

我正在使用 webpack 和包 dotenv-webpack https://www.npmjs.com/package/dotenv-webpack 在 gitignored .env 文件中设置 API_KEY 并且它在我的本地运行良好.我还希望能够在通过 Netlify 部署时设置该变量,我已经尝试将其添加到 GUI 中的构建环境变量",并直接在构建命令中进行设置,但没有成功.

I'm using webpack and the package dotenv-webpack https://www.npmjs.com/package/dotenv-webpack to set API_KEY in a gitignored .env file and it's all running fine on my local. I'd like to also be able to set that variable when deploying through Netlify, I've tried adding it through to GUI to the 'build environment variables', and also to set it directly in the build command, but without success.

知道可能是什么问题吗?

Any idea what might be the issue ?

推荐答案

警告:如果这是一个秘密密钥,您不会希望在返回给客户端的任何包中公开此环境变量值.它只应由您的构建脚本使用,用于在构建期间创建您的内容.

WARNING: If this is a secret key, you will not want to expose this environment variable value in any bundle that gets returned to the client. It should only be used by your build scripts to be used to create your content during build.

dotenv-webpack 期望有一个 .env 文件在你的包的 webpack 构建过程中加载到你的变量中.当 Netlify 检出存储库时,.env 不存在,因为它在 .gitignore 中有充分的理由.

dotenv-webpack expects there to be a .env file to load in your variables during the webpack build of your bundle. When the repository is checked out by Netlify, the .env does not exist because for good reason it is in .gitignore.

将您的 API_KEY 存储在 Netlify 构建环境变量 中,并在运行构建命令之前使用脚本构建 .env.

Store your API_KEY in the Netlify build environment variables and build the .env using a script prior to running the build command.

scripts/create-env.js

const fs = require('fs')
fs.writeFileSync('./.env', `API_KEY=${process.env.API_KEY}\n`)

将脚本作为构建的一部分运行

Run the script as part of your build

node ./scripts/create-env.js &&

  • 不要在面向公众的存储库中使用这种方法 [open] 因为任何 PR 或分支部署都可以在您的代码中创建一个简单的脚本来公开 API_KEY
  • 上面的示例脚本是为了简单起见,因此,让您使用的任何脚本都能够使用 0 以外的代码出错,这样如果脚本失败,部署就会失败.
  • Do not use this method with a public facing repository [open] because any PR or branch deploy could create a simple script into your code to expose the API_KEY
  • The example script above is for simplicity so, make any script you use be able to error out with a code other than 0 so if the script fails the deploy will fail.

这篇关于为 Netlify 中的构建设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆