conditionally render siteUrl property in Gatsby-config based on environment

后端 未结 3 2012
青春惊慌失措
青春惊慌失措 2021-01-24 12:30

I would like to set up a simple expression in my gatsby-config.js that determines whether I am working locally or in production so that I can set the siteUrl<

3条回答
  •  后悔当初
    2021-01-24 12:53

    You just need to set a .env.development and .env.production. Gatsby, by default, it will take the first one when you run a gatsby develop command and the second in gatsby build. Of course, you can change its behavior by changing your running script's command.

    Once you set your .env.development, it should look like:

    SITE_URL: https://www.google.com
    

    Then, this variable will be exposed in any Gatsby's file in the runtime. You only need to access it by:

    module.exports = {
        siteMetadata: {
            title: "My title",
            description: "My description...",
            siteUrl: process.env.SITE_URL
      }, {
         ... 
      }
    

    You can check the active environment by checking GATSBY_ACTIVE_ENV variable like:

    siteUrl: process.env.GATSBY_ACTIVE_ENV==='development' ? '/' : 'https://example.com'
    

    You can change the default behavior by changing the running script in your package.json. For example:

    "develop": "GATSBY_ACTIVE_ENV=whatever gatsby develop",
    

    Now, GATSBY_ACTIVE_ENV would be whatever in a develop mode.

    For further reading, check Gatsby's docs

提交回复
热议问题