LoginSignup
13
12

More than 5 years have passed since last update.

gulpでBEMの構文スタイルをチェックする

Last updated at Posted at 2016-07-01

BEMの構文チェックをgulpで行う方法を記載します。

前提条件

  • gulp実行環境がある

できること

以下のことができるようなgulpタスクを作成します。

準備

$ 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回以上連続して無駄に長くなってしまうのを防ぐことができるようになりました。

13
12
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
13
12