我们正在为所有推送的git分支使用Netlify的自动部署。
我们希望仅为主分支包含我们的分析脚本(等),即我们的用户正在访问的网站版本。
可以在Netlify上构建环境变量,但是如果可以区分某些分支的变量,我就无法获得?
答案 0 :(得分:6)
有一种方法可以在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网站上输入浏览器控制台的环境变量。