【问题标题】:Branch specific environment variables on NetlifyNetlify 上的分支特定环境变量
【发布时间】:2023-04-01 10:04:01
【问题描述】:

我们正在为所有推送的 git 分支使用 Netlify 的自动部署。

我们希望仅包含主分支的分析脚本(等),即我们的用户正在访问的网站版本。

可以在Netlify上构建环境变量,但我不知道是否可以区分某些分支的变量?

【问题讨论】:

    标签: git deployment environment-variables netlify static-html


    【解决方案1】:

    有一种方法可以在您的 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 的环境变量,它具有了解定义的上下文(生产、开发、部署)的值。构建语言现在可以访问这些变量来决定在构建结果中包含哪些内容。

    注意:

    • 使用您需要的任何环境变量名称和值。该示例以 Hugo 静态站点生成器为目标,该生成器具有函数 getenv 来检索值。
    • 我还没有测试过使用 context.branch-deploy 对自定义分支的影响,因此请注意覆盖这些上下文。
    • netlify.toml 中指定的任何变量都会覆盖在 Netlify 站点的浏览器控制台中输入的环境变量。

    【讨论】:

    • 请记住:环境变量也是特定于构建的,如果您需要在客户端的代码中使用它们,则必须在构建时将它们烘焙到您的代码中。
    • 嗯,你介意举个例子,代码中的 if 语句看起来像只在生产上下文中包含一个脚本标签吗?
    • Netlify 上的开发人员可以使用任意数量的解决方案,并支持构建支持的不同编码语言。针对您遇到的特定问题和您使用的编码语言提出一个单独的问题,以获得在代码中使用环境变量的正确建议。我将调整答案以解释如何使用上述设置。
    • 对于无法提交到 netlify.toml 文件的秘密环境变量,您将如何执行此操作?/
    • 将密钥存储在 app.netlify.com 控制台中。不幸的是,您将无法按上下文存储,因此必须为暂存分支创建一个单独的站点并在该站点中使用暂存密钥。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多