【发布时间】:2023-04-01 10:04:01
【问题描述】:
我们正在为所有推送的 git 分支使用 Netlify 的自动部署。
我们希望仅包含主分支的分析脚本(等),即我们的用户正在访问的网站版本。
可以在Netlify上构建环境变量,但我不知道是否可以区分某些分支的变量?
【问题讨论】:
标签: git deployment environment-variables netlify static-html
我们正在为所有推送的 git 分支使用 Netlify 的自动部署。
我们希望仅包含主分支的分析脚本(等),即我们的用户正在访问的网站版本。
可以在Netlify上构建环境变量,但我不知道是否可以区分某些分支的变量?
【问题讨论】:
标签: git deployment environment-variables netlify static-html
有一种方法可以在您的 netlify.toml 文件中的 Netlify 中设置 environment variables based on the deploy context。这是在使用 Hugo 的生产站点中使用的,但您可以为变量和命令使用任何您想要的键。
netlify.toml
# Global settings applied to the whole site.
[build]
command = "yarn build"
publish = "public"
# build a preview of the site (Drafts and Future dates also)
[context.deploy-preview]
command = "yarn build:preview"
[build.environment]
HUGO_ENV = "development"
[context.production.environment]
HUGO_VERSION = "0.29"
HUGO_ENV = "production"
# you can lock a version of hugo for a deploy preview
[context.deploy-preview.environment]
HUGO_VERSION = "0.29"
HUGO_ENV = "deploy" # TEST: should be deploy or something other than production
# you can lock a version of hugo for a branch-deploy (other than previews)
[context.branch-deploy.environment]
HUGO_VERSION = "0.30"
HUGO_ENV = "development"
还针对特定分支(例如:new-branch)
# build a preview of the site (Drafts and Future dates also)
[context.new-branch]
command = "yarn build:preview"
# you can also target a specific branch
[context.new-branch.environment]
HUGO_VERSION = "0.29"
HUGO_ENV = "deploy" # TEST: should be deploy or something other than production
解决方案:现在将有一个名为HUGO_ENV 的环境变量,它具有了解定义的上下文(生产、开发、部署)的值。构建语言现在可以访问这些变量来决定在构建结果中包含哪些内容。
注意:
getenv 来检索值。context.branch-deploy 对自定义分支的影响,因此请注意覆盖这些上下文。netlify.toml 中指定的任何变量都会覆盖在 Netlify 站点的浏览器控制台中输入的环境变量。【讨论】: