💡

Decapの設定ファイルを環境ごとに書き換える

2024/02/10に公開

Decap CMS(旧Netlify CMS)の設定ファイル(config.yml/config.yaml)を環境ごとに使い分ける方法を紹介します。Gatsbyjs(SSG) + Decapを利用している前提です。

config.ymlの内容はcms.jsで上書きすることができる

Decapのconfig.ymlでこんか感じの設定をしているとします。

config.yml
backend:
  name: github
  branch: main
site_url: https://example.com
collections:
  - name: hoge
  ... 各種設定

config.ymlで設定した内容をcms.jsで上書きすることができます。

cms.js
import CMS, { init } from 'decap-cms-app'

init({
  config: {
    backend: {
      // branchの内容を上書きする
      branch: 'develop',
    },
  },
})

この仕組みと環境変数 NODE_ENV を組み合わせるとこんな感じで環境ごとに設定を変更することができます。

cms.js
import CMS, { init } from 'decap-cms-app'

// gatsby developコマンド: NODE_ENV=development
// gatsby buildコマンド: NODE_ENV=productionが設定される
const env = process.env.NODE_ENV || 'development'

init({
  config: {
    backend: {
      // 環境ごとにbranchの内容を上書きする
      branch: env === 'production' ? 'main' : 'develop',
    },
  },
})

この方法を使えばGitHub Actionsでsedコマンドを使って無理やりファイルを書き換えたりしなくて良くなります。

Gatsbyのdecapプラグインの設定を忘れずに

cms.jsで設定を上書きするためには manualInit を true にセットする必要があります。

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-decap-cms`,
      options: {
        manualInit: true,
        modulePath: `${__dirname}/src/cms/cms.js`
      },
    }
  ],
}

development/production以外の環境を追加したいときはどうする

development/production以外にステージング環境を追加したい場合は一手間必要になります。以下のようにビルドコマンドから環境変数を設定することはできるのですが、cms.jsで環境変数 ENV を参照しても値がセットされません。

package.json
{
  "script": {
    "dev": "gatsby develop",
    "build": "gatsby build",
    "build.stg": "ENV=stg gatsby build"
  }
  ... その他設定
}

コマンド経由で設定したENV=stgはあくまで Gatsby のビルド時にしか参照できないためクライアントコードから環境変数を参照することができないです。そんなときに役に立つのがgatsby-plugin-env-variablesプラグインです。gatsby-config.js に gatsby-plugin-env-variablesプラグインの設定を追加してクライアントサイドにも環境変数を渡せるようにします[1]

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-decap-cms`,
      options: {
        manualInit: true,
        modulePath: `${__dirname}/src/cms/cms.js`
      },
    },
    {
      resolve: `gatsby-plugin-env-variables`,
      options: {
        // ENV環境変数をクライアントサイド(cms.js)に渡す
        allowList: ["ENV"]
      },
    },
  ],
}

cms.jsでこんな感じで環境変数 ENV にセットされた値を利用することができます。

cms.js
import CMS, { init } from 'decap-cms-app'

// ENVにstgが設定されている
const env = process.env.ENV || process.env.NODE_ENV || 'development'

const getBranch = (env) => {
  if (env == 'stg') return 'stg'
  if (env == 'development') return 'develop'
  return 'main'
}

const config = {
  backend: {
    branch: getBranch(env)
  }
}

init({ config })

Decapについて

Decap(旧NetlifyCMS)はデータベース不要、すべてGitHubで完結するHeadless CMSです。インフラコストを低く抑えたい時におすすめです。
https://decapcms.org/

参考

脚注
  1. プラグインの追加はpnpm add -D gatsby-plugin-env-variablesを実行してください。 ↩︎

Discussion