🌟

WordPressテーマのバージョン等をpackage.jsonに追従させる

2023/04/03に公開

WordPressの管理画面に表示されるバージョンや著者は、style.cssに書く仕様だが、如何せん書きづらい。そこで、PostCSSを使い、package.jsonをテーマ情報のソースとする。

前も書いた気がするが、アカウントを変えたので、Tailwind v3も想定して書き直した。

PostCSSの用意

yarn add -D npm-run-all postcss postcss-cli postcss-replace
postcss.config.js
const pack = require('./package.json');
const {
  name,
  description,
  author: { name: authorName },
  version,
  repository: { url: repositoryUrl },
} = pack;
const authorUrl = 'https://github.com/' + authorName;

module.exports = {
  plugins:
    process.env.BUILDING_META == 1
      ? {
          'postcss-replace': {
            data: {
              name,
              repositoryUrl,
              authorName,
              authorUrl,
              description,
              version,
            },
          },
        }
      : {
          /* 以下はTailwind V3を使う場合の一例 */
          // 'postcss-import': {},
          // 'tailwindcss/nesting': {},
          // 'postcss-simple-vars': {},
          // tailwindcss: {},
          // autoprefixer: {},
          // cssnano: {},
        },
};

postcss-replacedataに置換のkey: valueを渡す。かっこつけて分割代入している。

いや、読みづらいな... むしろkey: valueの方に普通に書いてもいいかもしれない。

テンプレートの用意

postcss/meta.css
/*
Theme Name: {{ name }}
Theme URI: {{ repositoryUrl }}
Author: {{ authorName }}
Author URI: {{ authorUrl }}
Description: {{ description }}
Version: {{ version }}
License: GNU General Public License v3
License URI: https://www.gnu.org/licenses/gpl-3.0.html
Text Domain: {{ name }}

GitHub Theme URI: {{ repositoryUrl }}
Primary Branch: main
Release Asset: true
*/

/* **注意** style.cssではなくpostcss/meta.cssを編集すること */

そして、postcss/meta.css など任意の場所にテンプレートを置く。

https://docs.npmjs.com/cli/v9/configuring-npm/package-json#license

https://developer.wordpress.org/themes/basics/main-stylesheet-style-css/

なお、ライセンスはあえてハードコーディングしている。

NPMの表記はSPDXライセンスIDとやらに従うらしいが、WordPressは英語でライセンス名を書くため、わざわざそこの整合性を取るコードは書かなかった。

書き出し

package.json
{
  "scripts": {
    "meta": "echo \"Updating theme info\" && BUILDING_META=1 postcss ./postcss/meta.css -o ./style.css",
    "production": "#ここにCSSビルドコマンド",
    "build": "run-s meta production"
  },
}

最後に、PostCSS CLIでstyle.cssを書き出す。

なお、実際のCSSをstyle.cssに書く想定はしていない。 PostCSSを使うということは、ビルド結果が存在する。実際のCSSはそこからロードしてくれ。

Discussion