やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

PostCSSをインストールする

 CSS開発環境のデファクト・スタンダードと思われる。

PostCSSとは

 PostCSSは、JSプラグインを使用してスタイルを変換するためのツールである。

なにができるか

 CSS開発するにあたりいくつかの工程がある。PostCSSはその工程すべてを自動化できる。

No 工程 概要
1 リント(静的チェック) 実行時エラーを事前に発見する
2 フォーマット コードを整形する
3 プリプロセッサ alt言語によりCSSファイルを出力する
4 ポストプロセッサ ベンダープレフィックス付与、サイズ圧縮、デプロイ自動化

 よって、SassやSCSSなどの候補より優れていると判断し、PostCSSをインストールすることにした。

 以下サイトを参考にした。

しくみ

 PostCSSCSSファイルを解析してその内容を取得・変更するAPIを提供するものである。そのため、PostCSSだけでは何もせず、プラグインが具体的な処理を行う。たとえばAutoPrefixerはベンダープレフィックスを自動挿入する。拡張まで入れてはじめて機能する。

前提

$ node -v
v16.14.2
$ npm -v
8.5.0

手順

 プロジェクト用ディレクトリを作り、そこへ移動する。とりあえず適当にhello-post-cssという名前にする。

PJ_NAME=hello-post-css
mkdir $PJ_NAME
cd $PJ_NAME

 プロジェクトをつくる。

npm init

 いろいろ質問されるが、Enterキー連打してデフォルト値にしておく。

 PostCSSをインストールする。

npm install -D postcss-cli

 バージョン確認する。

./node_modules/.bin/postcss --version
1.0.0

 ヘルプ確認する。

./node_modules/.bin/postcss --help

ヘルプ詳細

Usage:
  postcss [input.css] [OPTIONS] [-o|--output output.css] [--watch|-w]
  p
ostcss ... [OPTIONS] --dir  [--watch|-w]
  postcss
 [OPTIONS] --dir  [--watch|-w]
  postcss  [OPTIONS] --dir  [--watch|-w]
  postcss ... [OPTIONS] --replace

Basic options:
  -o, --output   Output file                                               [文字列]
  -d, --dir      Output directory                                          [文字列]
  -r, --replace  Replace (overwrite) the input file                         [真偽]
  -m, --map      Create an external sourcemap
      --no-map   Disable the default inline sourcemaps
  -w, --watch    Watch files for changes and recompile as needed            [真偽]
      --verbose  Be verbose                                                 [真偽]
      --env      A shortcut for setting NODE_ENV                           [文字列]

Options for use without a config file:
  -u, --use          List of postcss plugins to use                         [配列]
      --parser       Custom postcss parser                                 [文字列]
      --stringifier  Custom postcss stringifier                            [文字列]
      --syntax       Custom postcss syntax                                 [文字列]

Options for use with --dir:
      --ext   Override the output file extension; for use with --dir       [文字列]
      --base  Mirror the directory structure relative to this path in the output
               directory, for use with --dir                               [文字列]

Advanced options:
      --include-dotfiles  Enable glob to match files/dirs that begin with "."
                                                                            [真偽]
      --poll              Use polling for file watching. Can optionally pass pol
                          ling interval; default 100 ms
      --config            Set a custom directory to look for a config file [文字列]

オプション:
      --version  バージョンを表示                                                   [真偽]
  -h, --help     ヘルプを表示                                                     [真偽]

例:
  postcss input.css -o output.css           Basic usage
  postcss src/**/*.css --base src --dir bu  Glob Pattern & output
  ild
  cat input.css | postcss -u autoprefixer   Piping input & output
  > output.css

If no input files are passed, it reads from stdin. If neither -o, --dir, or --re
place is passed, it writes to stdout.

If there are multiple input files, the --dir or --replace option must be passed.

Input files may contain globs (e.g. src/**/*.css). If you pass an input director
y, it will process all files in the directory and any subdirectories, respecting
 the glob pattern.

For more details, please see https://github.com/postcss/postcss-cli

 CSSファイルを配置するディレクトリをつくる。src/...は入力、dst/...は出力するCSSを配置する。

mkdir -p src/css
mkdir -p dst/css

 テスト用に適当なCSSファイルを作る。

echo 'body { writing-mode: vertical-rl; }' > src/css/style.css

 PostCSSコマンドを叩く。作ったCSSファイルを渡して変換したCSSを出力させてみる。今回はまだ拡張をいれていないから同じファイルが出力されるはずだが、どうなるかな?

pcss=./node_modules/.bin/postcss
input=./src/css
output=./dst/css
$pcss $input -d $output
body { writing-mode: vertical-rl; }

/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9jc3Mvc3R5bGUuY3NzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIiwiZmlsZSI6InNyYy9jc3Mvc3R5bGUuY3NzIiwic291cmNlc0NvbnRlbnQiOlsiYm9keSB7IHdyaXRpbmctbW9kZTogdmVydGljYWwtcmw7IH1cbiJdfQ== */

 ……標準出力された。いやいや、ファイル出力しろやハゲ! なんのために出力先を指定したと思ってんだよバカ!

 まあいいや。とりあえず拡張機能をインストールして、設定ファイルで指定して、リトライしてみよう。そうすれば出力されると信じて。

拡張をインストールする

 変数を使うための拡張postcss-simple-varsをインストールする。

npm install -D postcss-simple-vars

 プロジェクトディレクトリのルートに以下のような設定ファイルを作成する。これでpostCSSが拡張機能を使えるようになる。

postcss.config.js

module.exports = {
  plugins: [
    require('postcss-simple-vars')(),
  ]
}

 変数を使ったpostCSSを書いてみる。

src/css/style-var.css

$writing-mode: vertical-rl;
body { writing-mode: $writing-mode; }

 これをCSSに変換する。

pcss=./node_modules/.bin/postcss
input=./src/css
output=./dst/css
$pcss $input -d $output

 これで以下のように出力された。

dst/css/style-var.css

body { writing-mode: vertical-rl; }

 よし、今度はちゃんとdstディレクトリに出力された。

 変数もOK。指定した値に置き換わっている。

 どうやらpostCSSはひとつ以上の拡張を使ったときファイル出力されるらしい。逆に拡張をひとつも使わないと標準出力になってしまうようだ。

蛇足

 postCSSコマンドを実行したらエラーになってちょっとハマった。

 変数定義の末尾にセミコロン;を付け忘れたらUndefined variableとかいうエラーになる。こいつがわかりにくい。未定義の変数という意味だが、ちゃんと定義してるやろ!って思ってしまう。よくよくみると、末尾のセミコロンがなくて、ちゃんと変数定義の命令が完了していなかったというオチ。

CssSyntaxError: postcss-simple-vars: /tmp/work/hello-post-css/src/css/style-var.css:5:1: Undefined variable $writing-mode

> 1 | $writing-mode: vertical-rl
    | ^
  2 | body { writing-mode: $writing-mode; }

 ようするに変数定義するときは以下のようなフォーマットにすればいい。でも末尾のセミコロンはついつい忘れがち。JSだとあってもなくてもいいのだが、CSSだとダメらしい。

$任意の変数名;

 ついでに、変数名にはハイフン-も使えた。ありがたい。

拡張

 ほかにも色々な拡張がある。以下を参照するとよい。

 きちんと環境構築するにはどの拡張を使うか吟味する必要がある。ものすごく大変そう。ざっと見た感じ、以下のようなものが良さそうだった。

拡張 概要
postcss-import 複数のCSSファイルを結合する(他の拡張がこれに依存していることが多いらしい)
postcss-autoreset リセットCSSを管理する?
autoprefixer ベンダープレフィックスを追加する
postcss-preset-env 新機能を使えるようにする
cssnano サイズ圧縮する(minify)

 コード整形はprettierを使うのがよさそう。

 私としてはlch()関数がほしかったなぁ。ここで紹介されてて便利そうなんだよね。ググったら見つけた。

 それぞれの拡張にあわせてインストールし、設定を入力せねばならない。

npm install -D 拡張名

postcss.config.js

module.exports = {
  plugins: [
    require('拡張名')(),
  ]
}

 べらぼうに大変だと思う。とくに設定はそれぞれの拡張ごとにGitHubのREADMEなどの資料を読んでゴリゴリ書いていくことになるだろう。バージョンが変わったら使えなくなってエラーが出たり、書き方も変わったりするんだろうな。時間がたったらCSS規格が更新されてブラウザに実装されるんだろうな。そのときはまた対応を迫られるんだろうな。嫌だなぁ。面倒くさいなぁ。そういうのも自動化してくれないかなぁ。

所感

 とりあえず一応できた。完成形には程遠いが。今はこれでいいや。

対象環境

$ uname -a
Linux raspberrypi 5.10.63-v7l+ #1496 SMP Wed Dec 1 15:58:56 GMT 2021 armv7l GNU/Linux