niksy / eslint-config-nitpick

ESLint config for my projects.
MIT License
2 stars 0 forks source link

Create plugin for pet peeves #24

Closed niksy closed 4 years ago

niksy commented 6 years ago
niksy commented 6 years ago

Example rule:

const ruleComposer = require('eslint-rule-composer');
const eslint = require('eslint');
const noUnusedExpressionsRule = new eslint.Linter()
    .getRules()
    .get('space-in-parens');

module.exports = {
    'space-in-parens-only-in-function-declaration-expression': ruleComposer.filterReports(
        noUnusedExpressionsRule,
        (problem, metadata) => {
            const rangeIndex = metadata.sourceCode.getIndexFromLoc(
                problem.loc.start
            );
            const realNode = metadata.sourceCode.getNodeByRangeIndex(
                rangeIndex
            );
            if (metadata.options[0] === 'always') {
                if (
                    realNode.type === 'FunctionExpression' ||
                    realNode.type === 'FunctionDeclaration' ||
                    realNode.type === 'ArrowFunctionExpression'
                ) {
                    return true;
                }
                return false;
            }
            return true;
        }
    )
};

Example code:

function a(a) {}

var c = function(a) {};

var d = (b) => {};

a(a);

var a = b();

1, 2;

ESLint RC

module.exports = {
    parserOptions: {
        ecmaVersion: 2015
    },
    plugins: ['local-rules'],
    rules: {
        'space-in-parens': 0,
        'local-rules/space-in-parens-only-in-function-declaration-expression': [
            2,
            'always'
        ]
    }
};

package.json

{
    "devDependencies": {
        "eslint": "^5.0.1",
        "eslint-plugin-local-rules": "^0.1.0",
        "eslint-rule-composer": "^0.3.0"
    }
}
niksy commented 6 years ago

Rule: Always use try/catch with JSON.parse

export default function(context) {
    return {
        MemberExpression(node) {
            if (node.object.name === 'JSON' && node.property.name === 'parse') {
                const isInTryCatchBlock = context
                    .getAncestors()
                    .some((node) => node.type === 'TryStatement');
                if (!isInTryCatchBlock) {
                    context.report(node, 'frende');
                }
            }
        }
    };
}