超簡単に stylelint を試す

stylelint

CSS/SCSS 用の Lint ツールとして stylelint がある。 手元にあるプロジェクトの CSS/SCSS を LInt ツールにかけたいが、環境構築にあまり時間をかけたくない。

特に

  • プロジェクトの構成を変更したくない、stylelint の導入のためだけに package.json の導入とかはしたくない
  • ルールを細かく設定したくない。なるべくデフォルトでいい感じにして欲しい

というワガママを叶えたまま、手元の CSS/SCSS をチェックする方法を調べてみた。

環境

  • stylelint@10.1.0
  • stylelint-config-standard@18.3.0

設定手順

まずは stylelint と stylelint-config-standard をグローバルにインストールする。

$ npm i -g stylelint stylelint-config-standard

次にルールファイルを作る。これもグローバルに設定する。

$ vim ~/.stylelintrc
{
  "extends": "stylelint-config-standard"
}

たったこれだけで stylelint コマンドが実行できるようになった。

実行手順

stylelint に CSS/SCSS ファイルのパスを渡すだけでできる

$ stylelint app/assets/stylesheets/**.scss

app/assets/stylesheets/application.scss
 10:1   ✖  Expected empty line before rule                           rule-empty-line-before
 16:16  ✖  Expected single space after "{" of a single-line block    block-opening-brace-space-after
 16:41  ✖  Expected single space before "}" of a single-line block   block-closing-brace-space-before
 17:22  ✖  Expected single space after "{" of a single-line block    block-opening-brace-space-after
 17:35  ✖  Expected single space before "}" of a single-line block   block-closing-brace-space-before
 17:35  ✖  Expected a trailing semicolon                             declaration-block-trailing-semicolon

自動で修正まで行う場合には --fix オプションを渡す。

$ stylelint app/assets/stylesheets/**.scss --fix

まとめ

簡単に stylelint でチェックできるようになったので、自分の書いた分くらいはチェックしてからコミットできるようになった。 ちゃんとやるならルールファイルをリポジトリにコミットしておくのがよいと思う。