「stylelint」の基本の使い方
CSS版のLintである「stylelint」を使ってみる。
まず、環境の準備から。
最小限の構成で、試しに使ってみることを想定している。
npmパッケージの準備。
% yarn init -y % yarn add -D stylelint % yarn add -D stylelint-config-standard
「stylelint-config-standard」は基本のルール。
この時点のディレクトリ構成
. ├── node_modules ├── package.json ├── yarn-error.log └── yarn.lock
「.stylelintrc」を作成する。
touch .stylelintrc
「.stylelintrc」に以下の内容を入力する。
{ "extends": "stylelint-config-standard" }
チェックしたいCSSファイル「hello.css」を用意する。
.hello { font-size: 20px; color: #000; padding: 5px; }
ルール違反として引っかかるよう、以下のとおり変更する。
.hello { font-size: 20p; color: #00000; padding: 5px; }
「test_css」ディレクトリを作り、配下に「hello.css」を置く。
ここまでの操作でのディレクトリ構成。
. ├── .stylelintrc ├── node_modules ├── package.json ├── test_css │ └── hello.css ├── yarn-error.log └── yarn.lock
「stylelint」を実行する。
方法1
npx stylelint test_css/*css
出力結果
test_css/hello.css 2:14 ✖ Unexpected unknown unit "p" unit-no-unknown 3:10 ✖ Unexpected invalid hex color "#00000" color-no-invalid-hex 4:5 ✖ Expected indentation of 2 spaces indentation
方法2
「package.json」を編集し、"scripts"のエントリを加える。
{ "name": "stylelint", "version": "1.0.0", "main": "index.js", "license": "MIT", "devDependencies": { "stylelint": "^13.0.0", "stylelint-config-standard": "^19.0.0" }, "scripts":{ "stylelint": "stylelint test_css/*css" } }
実行する。
npm run stylelint
出力結果。
test_css/hello.css 2:14 ✖ Unexpected unknown unit "p" unit-no-unknown 3:10 ✖ Unexpected invalid hex color "#00000" color-no-invalid-hex 4:5 ✖ Expected indentation of 2 spaces indentation npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! stylelint@1.0.0 stylelint: `stylelint test_css/*css` npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the stylelint@1.0.0 stylelint script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /home/theatermask/.npm/_logs/2020-01-31T12_18_52_918Z-debug.log
"npm ERR!"が出る。
"Exit status 2"の意味は以下のとおり。
2: At least one rule with an "error"-level severity triggered at least one violations.
https://stylelint.io/user-guide/cli#exit-codes
ルール違反があったことを示す。
気になるようなら、「package.json」を以下のとおり変更すればよい。
"scripts":{ "stylelint": "stylelint test_css/*css || echo 'return code: '$?" }
出力はこうなる。
test_css/hello.css 2:14 ✖ Unexpected unknown unit "p" unit-no-unknown 3:10 ✖ Unexpected invalid hex color "#00000" color-no-invalid-hex 4:5 ✖ Expected indentation of 2 spaces indentation return code: 2