Steve Tomlin Steve Tomlin - 1 month ago 14
Sass (Sass) Question

stylelint - Where are there examples to create your own plugin?

I have gone to the stylelint website, github and downloaded locally via npm. The stylelint website advises that to create my own plugin I should use this format:

var myPluginRule = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptionObject) {
return function(postcssRoot, postcssResult) {
var validOptions = stylelint.utils.validateOptions(postcssResult, ruleName, { .. })
if (!validOptions) { return }
// ... some logic ...
stylelint.utils.report({ .. })
}
})


When I do a 'find' inside the npm folder for stylelint, I cannot find any examples that use this format. Can anyone advise a really good tutorial on creating your own plugin?

thanks

Answer

ok after playing around with it I have literally found a way.

1) prerequisites:

$ npm init
$ npm install gulp stylelint gulp-style-lint --save-dev

2) Create some scss files at ./scss/myfile.scss

body{background:red;}

3) create ./gulpfile.js

var gulp          = require('gulp');
var gulpStylelint = require('gulp-stylelint');

gulp.task('stylelint',function(){
  return gulp        
    .src('./scss/*.scss')
    .pipe(
      gulpStylelint({
        reporters: [
          {formatter: 'string', console: true}
        ]
      })
    );
})

4) create ./stylelintCustom/index.js

var stylelint = require("stylelint");
var ruleName = "steves/steve1";

var messages = stylelint.utils.ruleMessages(ruleName, {
  rejected: 'steve rejects this',
});

module.exports = stylelint.createPlugin(ruleName, function(max, options) {

    return function(root, result) {     
      // to access the variable for the whole of this file scss =           
      console.log(root.source.input);

      // apply rules now...
      // run reporter to output

    }
});

module.exports.ruleName = ruleName;
module.exports.messages = messages;

Being sure to name ruleName: "plugins/plugin". ie steves/steverule1 etc.

5) Be sure to create stylelintCustom/package.json

{
  "name": "stylelint-steves-steve1", 
  "version": "0.0.1",
  "main": "index.js",
  "devDependencies": {
    "stylelint": "~2.6.0"
  },
  "engines": {
    "node": ">=0.10.0"
  }
}

6) create: stylelint.rc

{
  "plugins": [
    "./stylelintCustom/index.js"
  ],
  "rules": {
    "steves/steve1": true
  }
}

7) run gulp

$ gulp stylelint

Will output the scss, so you can run whatever js, regex you need here.