DEV Community

Alex Spinov
Alex Spinov

Posted on

ESLint Has a Free API — Here's How to Lint and Fix JavaScript Programmatically

ESLint is the standard JavaScript linter with 200+ built-in rules and a rich plugin ecosystem. The new flat config format makes it simpler than ever.

Installation

npm install -D eslint
npx eslint --init
Enter fullscreen mode Exit fullscreen mode

Flat Config (eslint.config.js)

import js from "@eslint/js";
import tseslint from "typescript-eslint";

export default [
  js.configs.recommended,
  ...tseslint.configs.recommended,
  {
    rules: {
      "no-unused-vars": "warn",
      "no-console": ["error", { allow: ["warn", "error"] }],
      "prefer-const": "error",
      "@typescript-eslint/no-explicit-any": "warn"
    }
  },
  {
    ignores: ["dist/", "node_modules/", "*.config.js"]
  }
];
Enter fullscreen mode Exit fullscreen mode

Running ESLint

npx eslint src/             # Lint files
npx eslint src/ --fix        # Auto-fix issues
npx eslint src/ --format json # JSON output
Enter fullscreen mode Exit fullscreen mode

Programmatic API

import { ESLint } from "eslint";

const eslint = new ESLint({ fix: true });

// Lint files
const results = await eslint.lintFiles(["src/**/*.ts"]);

// Apply fixes
await ESLint.outputFixes(results);

// Format results
const formatter = await eslint.loadFormatter("stylish");
console.log(await formatter.format(results));

// Get summary
const totalErrors = results.reduce((sum, r) => sum + r.errorCount, 0);
const totalWarnings = results.reduce((sum, r) => sum + r.warningCount, 0);
console.log(`${totalErrors} errors, ${totalWarnings} warnings`);
Enter fullscreen mode Exit fullscreen mode

Custom Rules

export default {
  meta: {
    type: "suggestion",
    docs: { description: "Disallow TODO comments" },
    fixable: null,
    schema: []
  },
  create(context) {
    return {
      Program() {
        const comments = context.sourceCode.getAllComments();
        comments.forEach(comment => {
          if (comment.value.includes("TODO")) {
            context.report({ node: comment, message: "Resolve TODO before committing" });
          }
        });
      }
    };
  }
};
Enter fullscreen mode Exit fullscreen mode

Popular Plugins

npm install -D eslint-plugin-react eslint-plugin-react-hooks
npm install -D eslint-plugin-import
npm install -D eslint-plugin-jsx-a11y
Enter fullscreen mode Exit fullscreen mode

Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)