Skip to content
This repository was archived by the owner on Mar 23, 2024. It is now read-only.

Plugin API

zxqfox edited this page Nov 11, 2014 · 11 revisions

Plugin example

./lib/index.js Configuration:

/**
 * @param {Configuration} conf
 */
module.exports = function (conf) {
  // plugin loading:
  conf.registerRule(require('./rules/your-rule.js'));
  conf.registerPreset('red-moo', require('../presets/red-moo-preset.json'));
  // conf.registerReporter('moonlight', require('./reporters/moonlight.js'));
};

./package.json:

{
  "devDependencies": {
    "jscs": ">=1.8.0 <2.0.0"
  },
  "peerDependencies": {
    "jscs": ">=1.8.0 <2.0.0"
  }
}

./lib/rules/your-rule.js (here you can take a look at rules in jscs repo):

module.exports = function () {};
module.exports.prototype.getOptionName = function () {
  return 'yourRule';
};
module.exports.prototype.configure = function (options) {
  assert(options === true || typeof options === 'object');
  // rule preparation and configuration
  this._options = options;
};
module.exports.prototype.check = function (file, errors) {
  // checking file
  if (this._options.color === 'red') {
    errors.add('red color', 1, 0);
  }
  file.iterate(function(node, parentNode, parentCollection) {
    if (!isValid(node)) {
      errors.add('invalid node found', node.loc.start);
    }
  });
  if (true) { // add an error
    errors.add('some error', 1, 0);
  }
};

./presets/red-moo-preset.json (presets in jscs repo):

{
  "yourRule": {
    "color": "red"
  }
}

./lib/reporters/moonlight.js (Errors, reporters):

/**
 * @param {Errors[]} errorsCollection
 */
module.exports = function(errorsCollection) {
    /**
     * Formatting every error set.
     */
    errorsCollection.forEach(function(errors) {
        if (!errors.isEmpty()) {
            /**
             * Formatting every single error.
             */
            errors.getErrorList().forEach(function(error) {
                console.log(errors.explainError(error) + '\n');
            });
        }
    });
};

Using your plugin

To load plugin you should just add it to plugins (or add your rules to additionalRules before v1.8):

.jscsrc with plugins list

{
  "plugins": ["your-plugin-package-name"],
  "yourRule": true
}

.jscsrc with additionalRules list

{
  "additionalRules": ["node_modules/your-plugin-package-name/lib/rules/*.js"],
  "yourRule": true
}

Via --reporter CLI option you can pass your own reporter:

jscs --reporter=./node_modules/your-plugin-package-name/lib/reporters/moonlight.js
Clone this wiki locally