BEMの構文チェックをgulpで行う方法を記載します。
前提条件
- gulp実行環境がある
できること
以下のことができるようなgulpタスクを作成します。
- gulp-notifyでNGとなった場合に通知される
- stylelintでcssのスタイルチェックを行う
- postcss-bem-linterでbemの構文チェックを行う
- postcss-reporterでチェック結果をコンソールに出力する
準備
$ gulp i -D gulp-postcss postcss-reporter stylelint postcss-bem-linter gulp-notify
実装例
gulpタスクの実装例を記載します。
gulpfile.js
const gulp-plumber = require('gulp-plumber'),
gulp-notify = require('gulp-notify'),
stylelint = require('stylelint'),
bemLinter = require('postcss-bem-linter'),
reporter = require('postcss-reporter')
gulp.task('stylelint', () => {
return gulp.src(paths.sass)
.pipe(gulp-plumber({ // ---- (1)
errorHandler: gulp-notify.onError(getNotifyConfig({
title: "Error running stylelint"
}))
}))
.pipe(gulp-postcss([ // ---- (2)
stylelint({ // ---- (3)
configFile: './.config/.stylelintrc',
}),
bemLinter({ // ---- (4)
preset: 'bem',
componentName: /^[a-zA-Z]+$/,
componentSelectors: (componentName) => {
const WORD = '[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*',
AMPERSAND = '(?:\&)*',
ELEMENT = '(?:__' + WORD + '){0,2}',
MODIFIER = '(?:--' + WORD + ')?',
OTHERCLASS = '(?:\s\\.[a-zA-Z]+)?',
ATTRIBUTE = '(?:\\[.+\\])?'
regex = '^' + '\\.' + componentName + ELEMENT + MODIFIER + ATTRIBUTE + OTHERCLASS + '$';
return new RegExp(regex)
}
}),
reporter({ // ---- (5)
throwError: true,
clearMessage: true
})
], {syntax: sugarss})) // ---- (6)
});
(1) plumberのerrorHandlerにgulp-notifyを仕込み、watch中にエラーがあった場合に通知させます。
(2) gulp-postcssを定義します。引数の配列にpluginを定義することでpluginを使用することができます。
(3) stylelintをpostcssのpluginとして使用することができます。ルールは外部ファイル(.stylelintrc)に切り出していますが、特に変わった設定はしていません。
(4) 本題となるbem構文をチェックするためのbemの構文定義をしています。
キー名 | 説明 |
---|---|
preset | 構文の基本パターンをbem にするかsuit にするか選択することができます。https://github.com/suitcss/suit/blob/master/doc/naming-conventions.md#namespace-optional |
componentName | コンポーネント名(block)を正規表現で定義します。 |
componentSelectors | bemの構文を正規表現で定義します。 |
(5) report出力しています。
(6) postcssでどのスタイル(.scss, .sass, .less, ...)でチェックするかを定義しています。
https://github.com/postcss/postcss#syntaxes
今のところBEMの構文は必要最低限のことしかチェックしていませんので、今後変更する可能性はありますが、
とりあえずelementが3回以上連続して無駄に長くなってしまうのを防ぐことができるようになりました。