LoginSignup
0
1

More than 3 years have passed since last update.

VSCodeの保存のたびに`stylelint --fix`をする

Last updated at Posted at 2019-12-26

背景

VSCodeでSassやCSSを保存したタイミングでstylelintでフォーマットしたい。

2020/01/31追記
stylelint パッケージがフォーマットに対応しました。

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

これで保存時に stylelint --fix をしてくれます。
ありがたや。

それに伴い、以下で紹介しているパッケージが非公開になったりしています。

以下、過去記事

ちょっと前の情報ではPrettierを使って、

settings.json
{
  "prettier.stylelintIntegration": true
}

と書いて、Prettierを使ってフォーマットするという情報をよく見たが、この設定は廃止になってうまく動いていない様子。
そもそも、最近のお作法としては stylelint-prettier を使用し、PrettierをStylelintに内包してStylelint側でfixするという方法が推奨されています。

.stylelintrc
{
  "plugins": ["stylelint-prettier"],
  "rules": {
    "prettier/prettier": [true, {"singleQuote": true, "tabWidth": 4}]
  }
}

こんな感じで.stylelintrcにstylelint-prettierを入れてPrettierのルールを書いていく。

しかし、Eslint拡張の様にStylelint拡張には autoFixOnSave オプションが無いし、
stylelint-plusという autoFixOnSave オプションが付いた拡張もあるが、どうも保存の後にfixが走るみたいで画面がリフレッシュされずうまくいかなかった。

結論

で、他の拡張を色々試してたところvscode-stylelint-format拡張を使い formatOnSave すればうまくいって保存のたびに stylelint --fix をすることができました。

vscode-stylelint-format拡張はVSCodeのデフォルトフォーマッターに設定できる拡張なので、そのまま設定してしまうと全言語に設定されてしまいます。
なので、今回はSassに使いたかったので下記の様に言語を指定して設定。

settings.json
{
  "css.validate": false,
  "scss.validate": false,
  "stylelint.enable": true,
  "[scss]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "pqml.vscode-stylelint-format"
  }
}

.stylelintrcファイルがないと動かない拡張みたいなので、プロジェクトルートに.stylelintrcのルールの設定が必ず必要になります。
あとStylelint拡張ももちろん必要です。

0
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
0
1