1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Stylelintの導入

Posted at

はじめに

個人的なStylelintの使い方をメモしておく。

A mighty, modern linter that helps you avoid errors and enforce conventions in your styles.

Stylelintはスタイルにおけるエラーを回避し規約を強制するためのリンター。

Stylelintと便利なプラグインのインストール

Stylelint本体とプラグインをインストールする。

% npm i -D stylelint \
           stylelint-config-standard \
           stylelint-config-recess-order \
           stylelint-config-prettier \
           stylelint-order
  • stylelint-config-standardstylelint-config-recommendedを拡張したもの。GoogleやAirbnbのCSSスタイルガイドで使われているルールを有効にする。
  • stylelint-config-recess-order:Twitter社製ツールのRecessや、Bootstrapと同じようにCSSプロパティをソートする。
  • stylelint-config-prettierPrettierと衝突する可能性のあるルールを全てオフにする。
  • stylelint-order:Stylelintにおけるソート用のプラグイン。自分でソートのrulesを書くこともできるし、stylelint-config-recess-orderなどの、ソートのルールが定義されたコンフィグに沿ってソートすることもできる。

Stylelintの設定ファイルをjson形式で書く。

.stylelintrc.json
{
  "extends": [
    "stylelint-config-standard",
    "stylelint-config-recess-order",
    "stylelint-config-prettier"
  ],
  "plugins": [
    "stylelint-order"
  ]
}

VSCode での Stylelint

% npx stylelint --fix src/**/*.css

というようにcssファイルを編集するたびにnpxでStylelintを実行するのは大変なので、
VSCodeの拡張機能を使って、リアルタイムでエラーを表示し、cssファイルを保存するたびにStylelintを実行して、一部のエラーを自動で修正できるようにする。

この拡張機能をインストールすればリアルタイムでスタイルのエラーを表示してくれるようになり、settings.jsonに以下を記述すれば、ファイルの保存時に一部のエラーを自動で修正してくれるようになる。

.vscode/settings.json
{
  "editor.codeActionsOnSave": {
    "source.fixAll.stylelint": true,
  },
}

チームメンバーに拡張機能を推奨するには、以下をgitで管理しておけばok。

.vscode/extensions.json
{
  "recommendations": [
    "stylelint.vscode-stylelint"
  ]
}

lint-staged・husky と Stylelint

コミット時にStylelintを実行するために、以下のコマンドでlint-stagedhuskyをインストールする。

% npx mrm@2 lint-staged

このコマンドを実行すると、パッケージのインストールだけではなく、package.jsonへの初期設定を行い、huskyの各種ファイルを生成してくれる。
これだけで、コミット時にStylelintが実行されるようになる。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?