Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lint for a harry robert's BEM convention with stylelint?

PostCSS BEM Linter plugin needs component definition for each block which is a time consuming thing to do in a legacy project.

Is there a way to use stylelint to check for the classes pattern and show error in all stylesheets (.scss in my case) of the project without needing component definition in each file/block?

https://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/

.block {}
.block__element {}
.block--modifier {}
like image 203
Jitendra Vyas Avatar asked Apr 07 '17 07:04

Jitendra Vyas


1 Answers

I have a working example following on from @jeddy3 answer.
This is a copy of my stylelint.config.js

We override the bemSelector() function taken from https://github.com/postcss/postcss-bem-linter/blob/master/lib/preset-patterns.js

We use two dashes style instead of default BEM by changing the const modifier to match https://en.bem.info/methodology/naming-convention/#two-dashes-style

/**
 * @param {String} block
 * @param {Object} [presetOptions]
 * @param {String} [presetOptions.namespace]
 * @returns {RegExp}
 */
const bemSelector = (block, presetOptions) => {
  const ns = (presetOptions && presetOptions.namespace) ? `${presetOptions.namespace}-` : '';
  const WORD = '[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*';
  const element = `(?:__${WORD})?`;
  const modifier = `(?:--${WORD}){0,2}`;
  const attribute = '(?:\\[.+\\])?';
  return new RegExp(`^\\.${ns}${block}${element}${modifier}${attribute}$`);
}

module.exports = {
  extends: 'stylelint-config-recommended-scss',
  plugins: [
    'stylelint-selector-bem-pattern'
  ],
  rules: {
    'plugin/selector-bem-pattern': {
      preset: 'bem',
      componentSelectors: bemSelector
    }
  }
}
like image 191
minlare Avatar answered Sep 23 '22 17:09

minlare