Coder Social home page Coder Social logo

postcss-bem-linter's Introduction

PostCSS

Philosopher’s stone, logo of PostCSS

PostCSS is a tool for transforming styles with JS plugins. These plugins can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more.

PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba, and JetBrains. The Autoprefixer and Stylelint PostCSS plugins is one of the most popular CSS tools.


  Made in Evil Martians, product consulting for developer tools.


Sponsorship

PostCSS needs your support. We are accepting donations at Open Collective.

Sponsored by Tailwind CSS        Sponsored by ThemeIsle

Plugins

PostCSS takes a CSS file and provides an API to analyze and modify its rules (by transforming them into an Abstract Syntax Tree). This API can then be used by plugins to do a lot of useful things, e.g., to find errors automatically, or to insert vendor prefixes.

Currently, PostCSS has more than 200 plugins. You can find all of the plugins in the plugins list or in the searchable catalog. Below is a list of our favorite plugins — the best demonstrations of what can be built on top of PostCSS.

If you have any new ideas, PostCSS plugin development is really easy.

Solve Global CSS Problem

  • postcss-use allows you to explicitly set PostCSS plugins within CSS and execute them only for the current file.
  • postcss-modules and react-css-modules automatically isolate selectors within components.
  • postcss-autoreset is an alternative to using a global reset that is better for isolatable components.
  • postcss-initial adds all: initial support, which resets all inherited styles.
  • cq-prolyfill adds container query support, allowing styles that respond to the width of the parent.

Use Future CSS, Today

Better CSS Readability

Images and Fonts

Linters

  • stylelint is a modular stylesheet linter.
  • stylefmt is a tool that automatically formats CSS according stylelint rules.
  • doiuse lints CSS for browser support, using data from Can I Use.
  • colorguard helps you maintain a consistent color palette.

Other

  • cssnano is a modular CSS minifier.
  • lost is a feature-rich calc() grid system.
  • rtlcss mirrors styles for right-to-left locales.

Syntaxes

PostCSS can transform styles in any syntax, not just CSS. If there is not yet support for your favorite syntax, you can write a parser and/or stringifier to extend PostCSS.

  • sugarss is a indent-based syntax like Sass or Stylus.
  • postcss-syntax switch syntax automatically by file extensions.
  • postcss-html parsing styles in <style> tags of HTML-like files.
  • postcss-markdown parsing styles in code blocks of Markdown files.
  • postcss-styled-syntax parses styles in template literals CSS-in-JS like styled-components.
  • postcss-jsx parsing CSS in template / object literals of source files.
  • postcss-styled parsing CSS in template literals of source files.
  • postcss-scss allows you to work with SCSS (but does not compile SCSS to CSS).
  • postcss-sass allows you to work with Sass (but does not compile Sass to CSS).
  • postcss-less allows you to work with Less (but does not compile LESS to CSS).
  • postcss-less-engine allows you to work with Less (and DOES compile LESS to CSS using true Less.js evaluation).
  • postcss-js allows you to write styles in JS or transform React Inline Styles, Radium or JSS.
  • postcss-safe-parser finds and fixes CSS syntax errors.
  • midas converts a CSS string to highlighted HTML.

Articles

More articles and videos you can find on awesome-postcss list.

Books

Usage

You can start using PostCSS in just two steps:

  1. Find and add PostCSS extensions for your build tool.
  2. Select plugins and add them to your PostCSS process.

CSS-in-JS

The best way to use PostCSS with CSS-in-JS is astroturf. Add its loader to your webpack.config.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'postcss-loader'],
      },
      {
        test: /\.jsx?$/,
        use: ['babel-loader', 'astroturf/loader'],
      }
    ]
  }
}

Then create postcss.config.js:

/** @type {import('postcss-load-config').Config} */
const config = {
  plugins: [
    require('autoprefixer'),
    require('postcss-nested')
  ]
}

module.exports = config

Parcel

Parcel has built-in PostCSS support. It already uses Autoprefixer and cssnano. If you want to change plugins, create postcss.config.js in project’s root:

/** @type {import('postcss-load-config').Config} */
const config = {
  plugins: [
    require('autoprefixer'),
    require('postcss-nested')
  ]
}

module.exports = config

Parcel will even automatically install these plugins for you.

Please, be aware of the several issues in Version 1. Notice, Version 2 may resolve the issues via issue #2157.

Webpack

Use postcss-loader in webpack.config.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
            }
          },
          {
            loader: 'postcss-loader'
          }
        ]
      }
    ]
  }
}

Then create postcss.config.js:

/** @type {import('postcss-load-config').Config} */
const config = {
  plugins: [
    require('autoprefixer'),
    require('postcss-nested')
  ]
}

module.exports = config

Gulp

Use gulp-postcss and gulp-sourcemaps.

gulp.task('css', () => {
  const postcss    = require('gulp-postcss')
  const sourcemaps = require('gulp-sourcemaps')

  return gulp.src('src/**/*.css')
    .pipe( sourcemaps.init() )
    .pipe( postcss([ require('autoprefixer'), require('postcss-nested') ]) )
    .pipe( sourcemaps.write('.') )
    .pipe( gulp.dest('build/') )
})

npm Scripts

To use PostCSS from your command-line interface or with npm scripts there is postcss-cli.

postcss --use autoprefixer -o main.css css/*.css

Browser

If you want to compile CSS string in browser (for instance, in live edit tools like CodePen), just use Browserify or webpack. They will pack PostCSS and plugins files into a single file.

To apply PostCSS plugins to React Inline Styles, JSS, Radium and other CSS-in-JS, you can use postcss-js and transforms style objects.

const postcss  = require('postcss-js')
const prefixer = postcss.sync([ require('autoprefixer') ])

prefixer({ display: 'flex' }) //=> { display: ['-webkit-box', '-webkit-flex', '-ms-flexbox', 'flex'] }

Runners

JS API

For other environments, you can use the JS API:

const autoprefixer = require('autoprefixer')
const postcss = require('postcss')
const postcssNested = require('postcss-nested')
const fs = require('fs')

fs.readFile('src/app.css', (err, css) => {
  postcss([autoprefixer, postcssNested])
    .process(css, { from: 'src/app.css', to: 'dest/app.css' })
    .then(result => {
      fs.writeFile('dest/app.css', result.css, () => true)
      if ( result.map ) {
        fs.writeFile('dest/app.css.map', result.map.toString(), () => true)
      }
    })
})

Read the PostCSS API documentation for more details about the JS API.

All PostCSS runners should pass PostCSS Runner Guidelines.

Options

Most PostCSS runners accept two parameters:

  • An array of plugins.
  • An object of options.

Common options:

  • syntax: an object providing a syntax parser and a stringifier.
  • parser: a special syntax parser (for example, SCSS).
  • stringifier: a special syntax output generator (for example, Midas).
  • map: source map options.
  • from: the input file name (most runners set it automatically).
  • to: the output file name (most runners set it automatically).

Treat Warnings as Errors

In some situations it might be helpful to fail the build on any warning from PostCSS or one of its plugins. This guarantees that no warnings go unnoticed, and helps to avoid bugs. While there is no option to enable treating warnings as errors, it can easily be done by adding postcss-fail-on-warn plugin in the end of PostCSS plugins:

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-fail-on-warn')
  ]
}

Editors & IDE Integration

VS Code

Sublime Text

Vim

WebStorm

To get support for PostCSS in WebStorm and other JetBrains IDEs you need to install this plugin.

Security Contact

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

For Enterprise

Available as part of the Tidelift Subscription.

The maintainers of postcss and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

postcss-bem-linter's People

Contributors

andieelmes avatar ausminternet avatar bencripps avatar bezoerb avatar bjentsch avatar ceesgeene avatar chrisnicotera avatar davidtheclark avatar flip-it avatar foresightyj avatar hsnaydd avatar iliyazelenko avatar ismamz avatar jednano avatar kulmajaba avatar makarov-roman avatar necolas avatar seamusleahy avatar simonsmith avatar vyorkin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

postcss-bem-linter's Issues

Could the `ignoreSelectors` option take an array of regexes?

I'm working on the web dashboard for GoCardless, with a fair amount of css:- 115 SUIT components

Admittedly I'm trying to add this BEM linting to an already mature codebase, but I'd like to use the ignoreSelectors option to ignore quite a few different bits of hairy CSS that have crept in over time into some of the examples, so as a result it would be more convenient if it took an array of regexes, rather than just a single regex.

Something like this would be ideal:

bemLinter({
  preset: 'suit',
  ignoreSelectors: [
    /^\.t\w{1,4}.u-is-shown$/,
    /^h/d, \.u-text-\w{1,3}$/,
    /^\.?svg.*/
  ]
})

This would be great, as I'd be able to ignore all of the following CSS rules without having to ignore them each individually...

/* postcss-bem-linter: ignore */
table.u-is-shown {
  display: table !important;
}
/* postcss-bem-linter: ignore */
tr.u-is-shown,
tr.u-is-shown {
  display: table-row !important;
}
/* postcss-bem-linter: ignore */
td.u-is-shown,
th.u-is-shown {
  display: table-cell !important;
}

/* postcss-bem-linter: ignore */
h1, .u-text-xxl {
  font-size: var(--font-size-xxl);
}
/* postcss-bem-linter: ignore */
h2, .u-text-xl {
  font-size: var(--font-size-xl);
}
/* postcss-bem-linter: ignore */
h3, .u-text-l {
  font-size: var(--font-size-l);
}
/* postcss-bem-linter: ignore */
h4, .u-text-m {
  font-size: var(--font-size-m);
}
/* postcss-bem-linter: ignore */
h5, .u-text-s {
  font-size: var(--font-size-s);
}
/* postcss-bem-linter: ignore */
h6, .u-text-xs {
  font-size: var(--font-size-xs);
}

Plus all of the following...:

7220:1  ⚠  Invalid utility selector ".svg-icon-fill-color-text *" [postcss-bem-linter]
7224:1  ⚠  Invalid utility selector ".svg-icon-fill-color-meta *" [postcss-bem-linter]
7228:1  ⚠  Invalid utility selector ".svg-icon-fill-color-gray-xlight *" [postcss-bem-linter]
7232:1  ⚠  Invalid utility selector ".svg-icon-fill-color-primary *" [postcss-bem-linter]
7236:1  ⚠  Invalid utility selector ".svg-icon-fill-color-yellow *" [postcss-bem-linter]
7240:1  ⚠  Invalid utility selector ".svg-icon-fill-color-secondary *" [postcss-bem-linter]
7244:1  ⚠  Invalid utility selector ".svg-icon-fill-color-accent *" [postcss-bem-linter]
7248:1  ⚠  Invalid utility selector ".svg-icon-fill-color-gray *" [postcss-bem-linter]
7252:1  ⚠  Invalid utility selector ".svg-icon-fill-color-invert *" [postcss-bem-linter]
7258:1  ⚠  Invalid utility selector ".svg-icon-stroke-color-text *" [postcss-bem-linter]
7262:1  ⚠  Invalid utility selector ".svg-icon-stroke-color-meta *" [postcss-bem-linter]
7266:1  ⚠  Invalid utility selector ".svg-icon-stroke-color-primary *" [postcss-bem-linter]
7270:1  ⚠  Invalid utility selector ".svg-icon-stroke-color-secondary *" [postcss-bem-linter]
7274:1  ⚠  Invalid utility selector ".svg-icon-stroke-color-accent *" [postcss-bem-linter]
7278:1  ⚠  Invalid utility selector ".svg-icon-stroke-color-gray *" [postcss-bem-linter]
7282:1  ⚠  Invalid utility selector ".svg-icon-stroke-color-invert *" [postcss-bem-linter]
7328:1  ⚠  Invalid utility selector "svg.svg-icon-sm > g.svg-icon-md" [postcss-bem-linter]
7329:1  ⚠  Invalid utility selector "svg.svg-icon-sm > g.svg-icon-lg" [postcss-bem-linter]
7330:1  ⚠  Invalid utility selector "svg.svg-icon-md > g.svg-icon-sm" [postcss-bem-linter]
7331:1  ⚠  Invalid utility selector "svg.svg-icon-md > g.svg-icon-lg" [postcss-bem-linter]
7332:1  ⚠  Invalid utility selector "svg.svg-icon-lg > g.svg-icon-sm" [postcss-bem-linter]
7333:1  ⚠  Invalid utility selector "svg.svg-icon-lg > g.svg-icon-md" [postcss-bem-linter]
7337:1  ⚠  Invalid utility selector "svg.svg-icon.svg-icon-sm > g.svg-icon-lg" [postcss-bem-linter]
7338:1  ⚠  Invalid utility selector "svg.svg-icon.svg-icon-md > g.svg-icon-lg" [postcss-bem-linter]
7342:1  ⚠  Invalid utility selector "svg.svg-icon-sm:not(.svg-icon-md):not(.svg-icon-lg) > g.svg-icon-sm" [postcss-bem-linter]
7343:1  ⚠  Invalid utility selector "svg.svg-icon-md.svg-icon-sm > g.svg-icon-sm" [postcss-bem-linter]
7344:1  ⚠  Invalid utility selector "svg.svg-icon-lg.svg-icon-sm > g.svg-icon-sm" [postcss-bem-linter]
7348:1  ⚠  Invalid utility selector "svg.svg-icon-md:not(.svg-icon-sm):not(.svg-icon-lg) > g.svg-icon-md" [postcss-bem-linter]
7349:1  ⚠  Invalid utility selector "svg.svg-icon-sm.svg-icon-md > g.svg-icon-md" [postcss-bem-linter]
7350:1  ⚠  Invalid utility selector "svg.svg-icon-lg.svg-icon-md > g.svg-icon-md" [postcss-bem-linter]
7354:1  ⚠  Invalid utility selector "svg.svg-icon-lg:not(.svg-icon-sm):not(.svg-icon-md) > g.svg-icon-lg" [postcss-bem-linter]
7355:1  ⚠  Invalid utility selector "svg.svg-icon-sm.svg-icon-lg > g.svg-icon-lg" [postcss-bem-linter]
7356:1  ⚠  Invalid utility selector "svg.svg-icon-md.svg-icon-lg > g.svg-icon-lg" [postcss-bem-linter]

Cannot ignore custom property name

Custom component selectors can be ignored but custom property names cannot.

Quick example:

.Navigation {
  /* postcss-bem-linter: ignore */
  --paper-menu-selected-item: {
    color: #262626;
  };

  /* postcss-bem-linter: ignore */
  --paper-menu-background-color: #fff;
}

11:3 ⚠ Invalid custom property name "--paper-menu-background-color": a component's custom properties must start with the component name [postcss-bem-linter]

The first is properly ignored, the second is not.
Is there any other way to ignore custom property names?

TypeError: Cannot read property 'test' of undefined

I'm using postcss-bem-linter in my webpack configuration and everything is working find, defining blocks and all, until I define utilities:

/** @define utilities */

.MicrosoftMap .MapPushpinBase {
    cursor: pointer !important;
}
ERROR in ./~/css-loader!./~/postcss-loader!./styles/sheets/store-locator/index.css
Module build failed: TypeError: Cannot read property 'test' of undefined
    at Z:\project\node_modules\postcss-bem-linter\lib\validate-utilities.js:22:19
    at Array.every (native)
    at isValid (Z:\project\node_modules\postcss-bem-linter\lib\validate-utilities.js:21:20)
    at Z:\project\node_modules\postcss-bem-linter\lib\validate-utilities.js:11:9
    at Array.forEach (native)
    at module.exports (Z:\project\node_modules\postcss-bem-linter\lib\validate-utilities.js:10:18)
    at checkRule (Z:\project\node_modules\postcss-bem-linter\index.js:46:9)
    at Z:\project\node_modules\postcss-bem-linter\index.js:40:9
    at Array.forEach (native)
    at Z:\project\node_modules\postcss-bem-linter\index.js:37:14

Update to PostCSS 4.1

It's nifty new messages API is well-suited to linting. If I understand correctly (still have to look into it more), we'd be able to accumulate all the errors and show them all at once to the user, instead of throwing one error at a time.

Get build to pass

I don't understand the latest failure. Again, it's related to JSCS: looks like it didn't install properly on Travis (?), but I can't guess why.

May be that this would be solved with a switch to ESLint: #29

:nth-child(3n+1) marked as "Invalid component selector" (BEM)

This selector does not seem to be valid:

.home__services-item:nth-child(3n+1)

While this one does:

.home__services-item:nth-child(3n)

I think they should be validated the same. I'm getting this error:
Invalid component selector ".home__services-item:nth-child(3n+1)" [postcss-bem-linter]

working with postcss-cli

Is this configuration compatible with postcss-cli? It seems as though it's not. when doing:

postcss --use postcss-bem-linter --postcss-bem-linter.namespace "br" ./src/styles/main.css

I'm getting the error

[TypeError: Cannot read property 'initial' of undefined]

I assume it's because of this's plugin's unusual configuration signature - any thoughts?

[BEM] CSS animations - Invalid component selector

The BEM linter preset doesn't seem to like css animation statements. Do i have to escape that part of the file or move it to a separate file that isn't linted?

The following animation rule is in a file with this definition: /** @define gs-o-live-status */

@keyframes pulse {
    0% { opacity: 1; }
    50% { opacity: .3; }
    100% { opacity: 1; }
}

This is the error i get:

29:5    ⚠  Invalid component selector "0%" (selector-bem-pattern) [stylelint]
30:5    ⚠  Invalid component selector "50%" (selector-bem-pattern) [stylelint]
31:5    ⚠  Invalid component selector "100%" (selector-bem-pattern) [stylelint]
40:1    ⚠  Invalid component selector ".gs-o-live-status__icon #pulse" (selector-bem-pattern) [stylelint]

Also how do i make nested rules acceptable using the BEM preset? (see below)

40:1    ⚠  Invalid component selector ".gs-o-live-status__icon #pulse" (selector-bem-pattern) [stylelint]

Change `selector` to `componentSelector`

If #21 is merged, the references throughout to selector often no longer apply generally to selectors, but instead apply specifically to component selectors (as opposed to utility selectors). So a little renaming ought to be done, probably.

Support for custom class convention regexes?

Are you open to supporting user-defined regular expressions that define custom class naming conventions?

The name of the module would make less sense in that case (i.e. user's convention might not be BEM or BEMish) --- but it doesn't seem like it would be too hard to allow for the flexibility in this codebase.

Or do you think such an idea is fodder for a separate module?

(I would like to try to work on a pull request to this module, or start up a separate module, to make this happen.)

Settings for ignoring specific selectors

Would love an additional regex selector for ignoring classes like html.no-flexbox or html.is-loaded and other smaller state classes or fixes. Using /* postcss-bem-linter: ignore */ works but it can get messy fast with to many. Also it would be nice to keep gulp-plugins out of the code.

Does this sound like something usable to y'all? 🚀

NPM Push for new error style

Could you bump the version and do an npm publish? In 0.2.0, the old style of errors is used which causes file names to be omitted from error messages. The new style error messages can probably fix this. It's a commit made a few months ago so it would be awesome if we could use it

🐹

Quick way to override preset settings for block and modifiers?

I tend to use a modified version of BEM, where the modifier is defined with -- rather than _.
What's the easiest way for me to add this change to my config?

I'm using PostCSS, and the stylelint plugin, so i'd need to override it via a settings object, but i'm finding the docs a little overwhelming when using a config object like below:

  var stylelintConfig = {
    "plugins": [
      "stylelint-selector-bem-pattern"
    ],
    "rules": {
      "block-no-empty": true,
      "color-no-invalid-hex": true,

      "selector-bem-pattern": {
        "preset": 'bem',
        "componentName": "[a-z]+"
      }
    }
  };

Failing for no clear reason.

I'm trying to get the tool setup for a project. However, I keep having complete failure where I don't seem to be causing it.

I've created a minimal repository to focus down on the problem. It only takes the output CSS and runs it directly through the linter.

  1. bem preset is defined.
  2. mdl is configured as prefix.
  3. /* postcss-bem-linter: define appbar */ is defined right before the component in question.
  4. /* @end */ is defined after the component is completed.

Actual output:

 gulp style      
[21:31:02] Using gulpfile ~/Code/postcss-bem-lint-failure-test/gulpfile.js
[21:31:02] Starting 'style'...

appbar.css
18:1    ⚠  Invalid component selector ".mdl-appbar" [postcss-bem-linter]
33:1    ⚠  Invalid component selector ".mdl-appbar_colored" [postcss-bem-linter]
37:1    ⚠  Invalid component selector ".mdl-appbar_colored .mdl-appbar__title .mdl-appbar__title-text" [postcss-bem-linter]
40:1    ⚠  Invalid component selector ".mdl-appbar_clipped-drawer" [postcss-bem-linter]
45:1    ⚠  Invalid component selector ".mdl-appbar_non-fixed-drawer" [postcss-bem-linter]
46:1    ⚠  Invalid component selector ".mdl-appbar_fixed" [postcss-bem-linter]
52:1    ⚠  Invalid component selector ".mdl-appbar__actions" [postcss-bem-linter]
56:1    ⚠  Invalid component selector ".mdl-appbar__title" [postcss-bem-linter]
62:1    ⚠  Invalid component selector ".mdl-appbar__title-text" [postcss-bem-linter]
66:1    ⚠  Invalid component selector ".mdl-appbar__title-text:active" [postcss-bem-linter]
67:7    ⚠  Invalid component selector ".mdl-appbar__title-text:focus" [postcss-bem-linter]
70:1    ⚠  Invalid component selector ".mdl-appbar__drawer-toggle" [postcss-bem-linter]
71:3    ⚠  Invalid component selector ".mdl-appbar__action" [postcss-bem-linter]
80:1    ⚠  Invalid component selector ".mdl-appbar__drawer-toggle:active" [postcss-bem-linter]
81:5    ⚠  Invalid component selector ".mdl-appbar__drawer-toggle:focus" [postcss-bem-linter]
82:5    ⚠  Invalid component selector ".mdl-appbar__action:active" [postcss-bem-linter]
83:5    ⚠  Invalid component selector ".mdl-appbar__action:focus" [postcss-bem-linter]
86:1    ⚠  Invalid component selector ".mdl-appbar__row" [postcss-bem-linter]
97:1    ⚠  Invalid component selector ".mdl-appbar__row > .mdl-appbar__drawer-toggle + .mdl-appbar__title" [postcss-bem-linter]
102:5   ⚠  Invalid component selector ".mdl-appbar" [postcss-bem-linter]
107:5   ⚠  Invalid component selector ".mdl-appbar__drawer-toggle" [postcss-bem-linter]
113:5   ⚠  Invalid component selector ".mdl-appbar__drawer-toggle" [postcss-bem-linter]
114:3   ⚠  Invalid component selector ".mdl-appbar__action" [postcss-bem-linter]
120:5   ⚠  Invalid component selector ".mdl-appbar__actions:last-child" [postcss-bem-linter]
126:5   ⚠  Invalid component selector ".mdl-appbar__actions:last-child" [postcss-bem-linter]
132:5   ⚠  Invalid component selector ".mdl-appbar_fixed" [postcss-bem-linter]
138:5   ⚠  Invalid component selector ".mdl-appbar_non-fixed-drawer" [postcss-bem-linter]
143:5   ⚠  Invalid component selector ".mdl-appbar_non-fixed-drawer .mdl-appbar__title" [postcss-bem-linter]
147:5   ⚠  Invalid component selector ".mdl-appbar_non-fixed-drawer .mdl-appbar__drawer-toggle" [postcss-bem-linter]
151:5   ⚠  Invalid component selector ".mdl-appbar_non-fixed-drawer .mdl-appbar_fixed" [postcss-bem-linter]

[21:31:02] Finished 'style' after 53 ms

I may expect some errors, but certainly not mdl-appbar (the first error) being an invalid selector.

Any ideas what I'm doing wrong here? Anything I can do to help narrow in on the problem?

jscs errors

I just forked the repo, npm installed and ran npm test. I hit the following jscs errors:

Missing space after opening bracket at index.js :
    26 |function conformance(options) {
    27 |  return function (styles) {
    28 |    var firstNode = styles.nodes[0];
-----------------------------------------^
    29 |    var initialComment;
    30 |

Missing space before closing bracket at index.js :
    26 |function conformance(options) {
    27 |  return function (styles) {
    28 |    var firstNode = styles.nodes[0];
------------------------------------------^
    29 |    var initialComment;
    30 |

Missing space after opening bracket at index.js :
    47 |    }
    48 |
    49 |    var componentName = initialComment.match(RE_DIRECTIVE)[1].trim();
-------------------------------------------------------------------^
    50 |    var isStrict = initialComment.match(RE_DIRECTIVE)[2] === 'use strict';
    51 |

Missing space before closing bracket at index.js :
    47 |    }
    48 |
    49 |    var componentName = initialComment.match(RE_DIRECTIVE)[1].trim();
--------------------------------------------------------------------^
    50 |    var isStrict = initialComment.match(RE_DIRECTIVE)[2] === 'use strict';
    51 |

Missing space after opening bracket at index.js :
    48 |
    49 |    var componentName = initialComment.match(RE_DIRECTIVE)[1].trim();
    50 |    var isStrict = initialComment.match(RE_DIRECTIVE)[2] === 'use strict';
--------------------------------------------------------------^
    51 |
    52 |    validateRules(styles);

Missing space before closing bracket at index.js :
    48 |
    49 |    var componentName = initialComment.match(RE_DIRECTIVE)[1].trim();
    50 |    var isStrict = initialComment.match(RE_DIRECTIVE)[2] === 'use strict';
---------------------------------------------------------------^
    51 |
    52 |    validateRules(styles);

Missing space after opening bracket at lib/validate-properties.js :
    19 |function validateCustomProperties(styles, componentName) {
    20 |  styles.eachRule(function (rule) {
    21 |    if (!isValidRule(rule) || rule.selectors[0] !== ':root') { return; }
-----------------------------------------------------^
    22 |
    23 |    rule.eachDecl(function (declaration, i) {

Missing space before closing bracket at lib/validate-properties.js :
    19 |function validateCustomProperties(styles, componentName) {
    20 |  styles.eachRule(function (rule) {
    21 |    if (!isValidRule(rule) || rule.selectors[0] !== ':root') { return; }
------------------------------------------------------^
    22 |
    23 |    rule.eachDecl(function (declaration, i) {


8 code style errors found.

The version of jscs installed is 1.10.0.

Maybe the rules or enforcement have changed since you last installed? In any case, I didn't want to make the changes myself because I figure code style is up to you, @necolas. Not sure whether you want those braces to have spaces inside or not.

Lint utility class stylesheets

Patterns could include a utilities regexp; and the directive at the top of utility stylesheets could inform the linter what it's looking at — maybe /** @define utilities */?

That way you could enforce utility class conventions in addition to those for component classes.

Refactor

Code can be simpler using the postcss api. Move patterns into a separate internal config to enable support for other BEM variations.

Should ignore files that have no nodes

I have some less templates that get processed into CSS files but actually output nothing. This gets normalized away eventually when my build process concatenates the individual CSS templates. I have the bem linter processing each individual file, not the final concatenated output, which means sometimes it runs against empty files (eg. less templates that contain only mixins and are not output). This causes an error in the linter because firstNode is undefined. Should the linter just ignore any CSS without nodes?

Maybe coming up on 1.0.0?

After pruning out the :root-selector checks (outsourcing them to stylelint), I think that this module is pretty focused: check selectors against regular expressions that are tailored by a special comment.

I don't see any bugs reported since May 11, so there's a good chance this means the intended functionality is working well for users.

Maybe that means we should have a 1.0.0 release.

My only hesitation is that I wonder whether other people think the API is unclear or weird or they have better ideas. If not, I think 1.0.0 release should come soon, probably after #57.

Make strict mode default

As discussed here: #13 (comment)

Unless anybody objects, it probably makes sense to make strict mode the default, and instead have users manually turn on a loose mode.

Some possibilities:

/** @define MyComponent; loose-mode */
/** @define MyComponent: loose */
/** @define:loose MyComponent */

Ability to process 1 CSS file with multiple components/blocks.

In our app, we are currently compiling .less files into 1 .css file. We'd like to use postcss-bem-linter and define where a component begins and ends via comments in our .less and have postcss-bem-linter run on this one file.

postcss-bem-linter already has support for defining a component via /** @define MyComponent */
Is it possible to add the ability to comment that a component's CSS has ended, /** @end MyComponent */

We are thinking something like:

my-compiled-file.css

`/** @define foo */`
.foo {
  ...
}

.foo--bar {
  ...
}
/** @end foo */

`/** @define baz */`

.baz {
  ...
}

.baz--bar {
  ...
}
/** @end baz */

Compatibility SASS nested rules?

I'm currently doing a spike to see how well this plugin fits in with our current development pipeline. I've currently got it running with PostCSS, Stylelint, and PostCSS-SCSS (to allow PostCSS to work with SASS files).

This plugin is working pretty nicely with SASS formatted CSS, but there are a few quirks. Ideally, i'd like to lint these files without having to compile/process them into raw CSS. The following scenario below demonstrates an issue where a selector nested inside another selector results in a BEM selector error.

Is this something that could be accommodated, or is it outside the scope of this project? It would be incredible if this was supported.

.gs-c-item-status--live {
    text-transform: uppercase;
    font-weight: bold;

    @include theme('sport') {
        color: $sp-c-live-blue;
    }

    @include theme('news') {
        color: $nw-c-red;
    }

    &.gs-c-item-status--on-dark {
        @include theme('sport') {
            color: $sp-c-live-blue-on-dark;
        }
    }
}

Error reported:

[14:14:45] Starting 'sass-lint'...

app/assets/_scss/components/_item-status.scss
25:5    ⚠  Invalid component selector "&.gs-c-item-status--on-dark" (selector-bem-pattern) [stylelint]

[14:14:45] Finished 'sass-lint' after 520 ms

Namespaced components produce a warning

Hey guys

Love the work you're doing on this.

I discovered that components named as per the optional SuitCSS namespace spec produce a warning in the output (if not an outright fail).

E.g. a component named ns-ComponentName produces the warning,

WARNING: invalid component name in definition

Is this by design? Or would you be open to PRs fixing the above?

Outsource :root-related checks to stylelint

stylelint has rules in place to check the two things that this linter currently checks (only custom properties in :root rules; :root cannot be combined with other selectors). So I figure this plugin may as well focus on its unique contribution --- checking selectors against dynamic regular expressions that know about component names --- and outsource that other business.

This would be a breaking change, of course.

Allow opting out on a per rule basis

I think it would be useful to tell bemlint to skip a rule if needed:

/* bemlint ignore:rule */
.no-flexbox .Component {
  display: block;
}

For me the use case is when I need to add some Modernizr fallbacks to a component and have to end up opting out of linting entirely to allow it to work. Moving the rules into a separate file also feels wrong.

Invalid component selector when importing blocks

Using postcss-import, which might be the root of the problem, I have a file that imports two blocks from separate CSS files like so:

@import block1;
@import block2;

Here are the contents of block1:

/** @define block1 */

.block1 {
    color: red;
}

And here are the contents of block2:

/** @define block2 */

.block2 {
    color: blue;
}

These, of course, get merged into one file with the imports, which is throwing an "Invalid component selector" error. postcss-bem-linter, expects only one block per file, but it sees them combined into one file, like so:

/** @define block1 */

.block1 {
    color: red;
}

/** @define block2 */

.block2 {
    color: blue;
}

Perhaps an option that allows one to have multiple blocks per file would resolve this issue? What do you think?

Doesn't work correct for me

My gulp task:

module.exports = function(gulp, plugins, growl) {
    gulp.task("postcss:dev", function() {
        var processors = [
            plugins.autoprefixerCore({
                browsers: ['last 2 versions'],
            }),
            plugins.postcssImport(),
            plugins.postcssNested(),
            plugins.cssnext(),
            plugins.postcssFontMagician(),
            plugins.postcssBemLinter(),
        ];
        return gulp.src(["assets/styles/**/+(main|vendor).css"])
            .pipe(plugins.postcss(processors))
            .pipe(gulp.dest(".tmp/public/styles"))
            .pipe(plugins.livereload())
            .pipe(plugins.if(growl, plugins.notify({ message: 'cssnext dev task complete' })));
        });
};

My page.css (this file imported to main.css):

/** @define Page */
.Page {
    display: flex;
    height: 100%;
    width: 100%;

    &--withPlugger {
        justify-content: center;
        align-items: center;
    }

    &-plugger {
        text-align: center;
    }
}
/* @end */

My main.css:

@import '../common/selectors';
@import '../common/general';

/*@import 'variables';*/
@import 'general';

@import 'components/page';

Other css file not contain @define directive.

Error:

postcss-bem-linter: /<PATH_TO_ASSETS>/styles/common/general.css:1:1: Invalid component selector "html"
postcss-bem-linter: /<PATH_TO_ASSETS>/styles/common/general.css:5:1: Invalid component selector "body"
postcss-bem-linter: /<PATH_TO_ASSETS>/styles/page/general.css:1:1: Invalid component selector "body"
postcss-bem-linter: /<PATH_TO_ASSETS>/styles/page/general.css:6:1: Invalid component selector "h1"
postcss-bem-linter: /<PATH_TO_ASSETS>/styles/page/general.css:6:1: Invalid component selector "h2"
postcss-bem-linter: /<PATH_TO_ASSETS>/styles/page/general.css:6:1: Invalid component selector "h3"
postcss-bem-linter: /<PATH_TO_ASSETS>/styles/page/general.css:6:1: Invalid component selector "h4"
postcss-bem-linter: /<PATH_TO_ASSETS>/styles/page/general.css:6:1: Invalid component selector "h5"
postcss-bem-linter: /<PATH_TO_ASSETS>/styles/page/general.css:6:1: Invalid component selector "h6"

compiled css:

html {
    height: 100%;
}

body {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    height: 100%;
    margin: 0;
    width: 100%;
}

body {
    background-color: white;
    font-family: 'Roboto';
}

h1,
h2,
h3,
h4,
h5,
h6 {
    font-family: 'Roboto Condensed';
}

/** @define Page */
.Page {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    height: 100%;
    width: 100%;

    &--withPlugger {
        -webkit-box-pack: center;
        -webkit-justify-content: center;
            -ms-flex-pack: center;
                justify-content: center;
        -webkit-box-align: center;
        -webkit-align-items: center;
            -ms-flex-align: center;
                align-items: center;
    }

    &-plugger {
        text-align: center;
    }
}
/* @end */

Sorry for my bad english.

Unable to get postcss-bem-linter to display any errors

I've created a simple demo of some message boxes using plain HTML and CSS - the CSS used is this:

/* postcss-bem-linter: define .content */

.dlgBox {
  border-radius: 0.625rem;
  padding: 0.625rem 0.625rem 0.625rem 2.375rem;
  margin: 0.625rem;
  width: 14.5rem; }

.dlgBox__alert {
  font-family: Tahoma, Geneva, Arial, sans-serif;
  font-size: 0.6875rem;
  color: #555;
  border-radius: 0.625rem; 
}

.dlgBox__alert.small span {
  font-weight: bold;
  text-transform: uppercase; 
}

.dlgBox__alert--error {
  background: #ffecec url("../img/error.png") no-repeat 0.625rem 50%;
  border: 0.0625rem solid #f5aca6; 
}

.dlgBox__alert--error:hover {
  opacity: 0.8; 
}

.dlgBox__alert--success {
  background: #e9ffd9 url("../img/success.png") no-repeat 0.625rem 50%;
  border: 0.0625rem solid #a6ca8a; 
}

.dlgBox__alert--success:hover {
  opacity: 0.8; 
}

.dlgBox__alert--warning {
  background: #fff8c4 url("../img/warning.png") no-repeat 0.625rem 50%;
  border: 0.0625rem solid #f2c779; 
}

.dlgBox__alert--warning:hover {
  opacity: 0.8; 
}

.dlgBox__alert--notice {
  background: #e3f7fc url("../img/info.png") no-repeat 0.625rem 50%;
  border: 0.0625rem solid #8ed9f6; 
}

.dlgBox__alert--notice:hover {
  opacity: 0.8; 
}

My issue is that I am unable to get postcss-bem-linter to show any errors - I've tried dropping one of the hyphens out of the rule, such as:

.dlgBox__alert-notice:hover {
  opacity: 0.8; 
}

...and one of the underscores as well, in a similar fashion. This is what I have in my gulpfile.js:

var gulp = require('gulp');
var postcss = require('gulp-postcss');
var bemLinter = require('postcss-bem-linter');
var reporter = require('postcss-reporter');

gulp.task('lint', function() {
  return gulp.src("src/*.css")
    .pipe(postcss([bemLinter({
        componentName: /[A-Z]+/
      }), reporter({
        formatter: function(input) {
          return input.source + ' produced ' + input.messages.length + ' messages';
        }
      })
    ]))
  .pipe(gulp.dest('/dest'));
});

gulp.task('default', ['lint']);

var watcher = gulp.watch('src/*.css', ['default']);
watcher.on('change', function(event) {
  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});

The only error I was able to get it to show was an "Invalid selector" one - I fixed this by adding the define: statement at the top of the CSS stylesheet. Can someone please point out where I'm going wrong? Each time I run the gulp task, I get a 0 messages confirmation from gulp-reporter, yet I am sure it should be showing something else...the version of PostCSS used is version 6.0.

New lint failures from the proposed 0.3.0 code

I just ran my project through the new linter based off the current state of the master branch before the proposed bump to 0.3.0 (as of 4cb6db8) and I'm getting a few new lint failures that I wasn't getting with 0.2.0.

Specifically the following selectors are all producing new failures where they weren't before,

.AuthCodeControl-input[type=number]
.Button[disabled]
.CheckControl-input[disabled] ~ .CheckControl-label
.TextControl-inner--password .TextControl-input[type="password"]

Are these selectors actually non-compliant and the new linting code properly picking them up, or is something going awry?

I'm just calling the linter with no additional options, like so,

postcss()
  .use(require('postcss-bem-linter')())
  .process(css);

Support default BEM syntax

Bake in support for default BEM syntax. Probably add a config option to pass in custom regexp's rather than trying to cater to all other flavours.

Update to PostCSS 4.1

It's nifty new messages API is well-suited to linting. If I understand correctly (still have to look into it more), we'd be able to accumulate all the errors and show them all at once to the user, instead of throwing one error at a time.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.