LoginSignup
42
34

More than 5 years have passed since last update.

stylelintの設定ファイルの作り方

Posted at

昨日は「stylelintとは何か」ということと、既存のCSSリンターと比べたときの特徴、CLIからstylelintを実行する方法について述べました。今日は、stylelintの数多くあるルールを組み合わせて設定ファイルを作る方法について述べます。

stylelintの設定ファイル

stylelintの設定のオブジェクトは cosmiconfig というパッケージを使って読み込まれます。stylelintの場合、以下のファイル名、形式で設定ファイルを作成できます。僕は、JSON形式で .stylelintrc という名前で作ることが多いです。

  • package.json 内の stylelint プロパティに記述する
  • .stylelintrc ファイル(JSON or YAML)
  • JSオブジェクトとして module.exports された stylelint.config.js ファイル

.stylelintrc 例:

{
  "rules": {
    "color-hex-length": "short",
    "color-no-invalid-hex": true,
    "custom-property-no-outside-root": true,
    "indentation": 2,
    "length-zero-no-unit": true,
    "media-feature-name-no-vendor-prefix": true,
    "number-leading-zero": "never",
    "selector-root-no-composition": true,
    "string-quotes": "single"
  }
}

次に設定オブジェクトのプロパティを見てみましょう。stylelintのルール名とそのオプションを、上記のように rules の中に指定します。

stylelintの設定ファイル集

npmで、stylelint-config のキーワードを付けて登録されているパッケージは、stylelintの設定集です。その中でも、以下のパッケージが有名です。

stylelintのルールは今約170個あり、それらを1つずつ調べて自分で1から設定ファイルを作るのは骨が折れます。
そこで、 stylelint-config-* パッケージを継承することで、公開されている設定ファイル集をベースに自分のプロジェクトでの調整を加えることができます。

{
  "extends": "stylelint-config-primer",
  "rules": {
    "indentation": 2,
    "string-quotes": "double"
  }
}

上記の例では、stylelint-config-primerextends し、インデントサイズと文字列のクォーテーションを変更しています。

stylelintのプラグイン

stylelintのルールは、全てPostCSSのプラグインとして実装されています。そこで開発者は、独自のstylelintのルールを作って、それをstylelintのプラグインとして公開することができます。

例として、SassのSCSS記法のための、stylelint-scss というプラグインがあります。

{
  "plugins": [
    "stylelint-scss"
  ],
  "rules": {
    "scss/dollar-variable-pattern": "^foo",
    "scss/selector-no-redundant-nesting-selector": true
  }
}

plugins プロパティで使いたいプラグインを指定することで、rules の中でその設定をすることができます。

ちなみに、facebookはstylelintの独自のルールを作って、CSSコードのクオリティを担保しているそうです。


今日はstylelintの設定ファイルの作り方について説明しました。設定ファイル集やプラグインを使うことで、さらにカスタマイズしやすくなっています。

42
34
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
42
34