【问题标题】:How can you use different configs when you build a website (gatsby build)构建网站时如何使用不同的配置(gatsby build)
【发布时间】:2021-07-22 23:23:54
【问题描述】:

我使用 gatsbyJS 和 prismic.io 作为无头 CMS 构建了一个静态网站。有谁知道在构建网站时如何使用不同的配置(gatsby build)(例如:gatsby config 1 / gatsby config 2)。最终目标是使用 Jenkins 自动构建具有相同代码库但不同 css/config 的不同站点。

【问题讨论】:

    标签: jenkins gatsby prismic.io


    【解决方案1】:

    嗯,它并不完全使用“不同的gatsby-config.js”文件,但最相似的方法是使用environment variables。这将允许您在不同的设置中使用相同的gatsby-config.js

    默认情况下,Gatsby 在分别运行 gatsby developgatsby build 时使用 developmentproduction 作为环境(您可以根据需要使用自定义环境覆盖此行为)。这样,您需要告诉 Gatsby 这些变量设置在哪里。这是由以下 sn-p 完成的(在 gatsby-config.js 中):

    require("dotenv").config({
      path: `.env.${process.env.NODE_ENV}`,
    })
    

    如果您在项目的根目录下创建.env.development.env.production,您可以这样做:

    GATSBY_API_URL=https://example.com/api
    API_KEY=927349872349798
    

    现在,在任何配置参数中,您都可以使用存储在这些文件中的环境变量,例如:

    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-patronus`,
          options: {
            apiKey: process.env.API_KEY,
          },
        },
      ],
    }
    

    扩展此行为,您可以自定义运行命令以使用不同的环境文件,例如 .env.siteOne.env.siteTwo,只需在 package.json 中更改和创建自己的脚本并使用 GATSBY_ACTIVE_ENV 变量:

     "scripts": {
        "build-site-one": "GATSBY_ACTIVE_ENV=siteOne gatsby build",
        "build-site-two": "GATSBY_ACTIVE_ENV=siteTwo gatsby build",
      },
    

    刚刚运行:

     npm run build-site-one
    

    您将获取存储在 .env.siteOne 文件中的环境变量,以便您可以指向不同的 CMS 配置、不同的主题、不同的路由和路径等。


    免责声明:整个过程旨在使用服务器端变量来更改某些配置/参数。要使用客户端 (JavaScript) 变量,您可以省略 require("dotenv").config({ path: `.env.${process.env.NODE_ENV}`}) 部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 2020-03-09
      • 2021-10-13
      • 2013-01-01
      • 1970-01-01
      • 2014-09-16
      • 2013-04-22
      相关资源
      最近更新 更多