or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

ESLint Loader

ESLint Loader is a webpack loader that integrates ESLint into the webpack build process, enabling automatic JavaScript code linting during compilation. It provides comprehensive ESLint integration with webpack bundling workflows, supporting features like caching for improved performance, configurable error and warning reporting, autofix capabilities, and flexible configuration options for customizing ESLint behavior within webpack builds.

Note: This package has been deprecated in favor of eslint-webpack-plugin for newer webpack versions.

Package Information

  • Package Name: eslint-loader
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install eslint-loader --save-dev
  • Peer Dependencies: eslint (^6.0.0 || ^7.0.0), webpack (^4.0.0 || ^5.0.0)

Core Imports

The package exports a single webpack loader function:

// CommonJS (most common usage in webpack configs)
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader'
      }
    ]
  }
};

For direct import (rarely needed):

const eslintLoader = require('eslint-loader');

ES6 module import:

import eslintLoader from 'eslint-loader';

Basic Usage

Simple Configuration

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader'
      }
    ]
  }
};

Pre-loader Usage (Recommended)

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader'
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      }
    ]
  }
};

With Options

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          cache: true,
          fix: true,
          emitWarning: true,
          failOnError: false
        }
      }
    ]
  }
};

Architecture

ESLint Loader is built around several key components that work together to integrate ESLint into webpack's build process:

  • Main Loader Function: Entry point that orchestrates the entire linting workflow within webpack's loader pipeline
  • Option Processing System: Validates and normalizes user-provided options using webpack's loader-utils and schema validation
  • ESLint Engine Management: Creates and caches ESLint CLIEngine instances for optimal performance across multiple files
  • Linter Processing Core: Handles the complete linting workflow including execution, filtering, autofix, and reporting
  • Caching Layer: Filesystem-based caching system that dramatically improves performance by avoiding redundant linting operations
  • Error Integration: Custom error types and webpack integration for seamless error/warning reporting in build process
  • Output Reporting: Flexible system for generating lint reports in various formats for CI/CD integration

Component Interaction Flow

  1. Webpack invokes loader → Main loader function receives file content and source map
  2. Option processinggetOptions() validates and processes configuration options
  3. Engine creationcreateEngine() provides cached ESLint CLIEngine instance
  4. Linter instantiationLinter class coordinates the linting workflow
  5. Cache check → If enabled, cacheLoader() checks for existing lint results
  6. ESLint executionLinter.lint() runs ESLint on source content
  7. Result processing → Filtering, autofix, and formatting of lint results
  8. Error reporting → Integration with webpack's error/warning emission system
  9. File output → Optional generation of lint reports for external consumption

Capabilities

Webpack Loader Function

The main export is a webpack loader function that processes JavaScript files through ESLint.

/**
 * Main webpack loader function for ESLint integration
 * @param {string} content - Source code content of the file being processed
 * @param {Object} map - Source map from previous loaders in the chain
 * @returns {void} - Uses webpack callback to pass through content and map
 * @this {LoaderContext} - Webpack loader context with emitError, emitWarning, cacheable methods
 */
function loader(content, map);

The loader function:

  • Validates and processes loader options using webpack's loader-utils
  • Creates internal Linter instance with ESLint CLIEngine
  • Handles caching if enabled through options
  • Runs ESLint on the source content
  • Reports linting results via webpack's emitError/emitWarning
  • Passes through original content and source map unchanged

Internal API Components

Option Processing

/**
 * Processes and validates webpack loader options
 * @param {Object} loaderContext - Webpack loader context
 * @returns {Object} - Validated and processed options with ESLint formatter
 */
function getOptions(loaderContext);

Processes loader options by:

  • Merging default options with user-provided options using loader-utils
  • Validating options against JSON schema using schema-utils
  • Loading ESLint CLIEngine from specified eslintPath
  • Resolving formatter functions from ESLint or custom formatters
  • Handling outputReport formatter resolution

ESLint Engine Management

/**
 * Creates or retrieves cached ESLint CLIEngine instance
 * @param {Object} options - ESLint configuration options
 * @returns {Object} - Object containing CLIEngine constructor and engine instance
 */
function createEngine(options);

Returns object with:

  • CLIEngine: ESLint CLIEngine constructor from specified eslintPath
  • engine: Cached ESLint engine instance (cached by options hash for performance)

Linter Class

/**
 * Main ESLint processing class that handles linting workflow
 * @param {Object} loaderContext - Webpack loader context
 * @param {Object} options - Processed loader options
 */
class Linter {
  constructor(loaderContext, options);
  
  /**
   * Execute ESLint on source content
   * @param {string} content - Source code to lint
   * @returns {Object} - ESLint results object
   */
  lint(content);
  
  /**
   * Process and report ESLint results
   * @param {Object} data - ESLint results from lint()
   * @returns {void}
   */
  printOutput(data);
  
  /**
   * Filter results based on quiet option
   * @param {Object} data - ESLint results
   * @returns {Object} - Filtered results
   */
  filter(data);
  
  /**
   * Apply ESLint autofix if enabled
   * @param {Object} res - ESLint results with fixable issues
   * @returns {void}
   */
  autoFix(res);
  
  /**
   * Generate report file if outputReport is configured
   * @param {Array} results - ESLint results array
   * @param {string} messages - Formatted lint messages
   * @returns {void}
   */
  reportOutput(results, messages);
  
  /**
   * Determine appropriate webpack emitter (error/warning)
   * @param {Object} lintResults - Object with errorCount property
   * @returns {Function} - Webpack emitError or emitWarning function
   */
  getEmitter(lintResults);
}

Cache Integration

/**
 * Handles caching of ESLint results for performance optimization
 * @param {Linter} linter - Linter instance
 * @param {string} content - Source content to cache
 * @param {Object} map - Source map from webpack
 * @returns {void} - Uses webpack async callback
 */
function cacheLoader(linter, content, map);

Caching workflow:

  • Generates cache identifier from eslint-loader and ESLint versions
  • Uses filesystem cache with compression for lint results
  • Falls back to linting if cache miss or error
  • Integrates with webpack's async callback system

Cache Module

/**
 * Filesystem cache implementation for ESLint results
 * @param {CacheParams} params - Cache configuration and data
 * @returns {Promise<ESLintResult>} - Cached or computed lint results
 */
function cache(params);

Cache features:

  • Compression: Uses gzip compression for cache files to save disk space
  • Fallback: Automatically falls back to temporary directory if node_modules is not writable
  • Versioning: Includes eslint-loader and ESLint versions in cache keys for proper invalidation
  • Hash-based: Uses MD4 hash of source, options, and identifier for unique cache file names
  • Error Recovery: Gracefully handles cache read/write errors with fallback strategies

Error Handling

/**
 * Custom error class for ESLint-related errors
 * @param {string} messages - Formatted error messages from ESLint
 */
class ESLintError extends Error {
  constructor(messages);
}

Properties:

  • name: Always "ESLintError"
  • stack: Set to false to prevent stack trace pollution
  • message: Contains formatted ESLint error messages

Configuration Options

All ESLint CLIEngine options are supported, plus these loader-specific options:

Cache Options

interface CacheOptions {
  /** Enable caching of linting results to improve performance */
  cache?: boolean | string;
}

Usage:

  • cache: true - Uses default cache directory ./node_modules/.cache/eslint-loader
  • cache: './.eslint-loader-cache' - Uses custom cache directory path

ESLint Integration Options

interface ESLintIntegrationOptions {
  /** Path to ESLint instance to use for linting */
  eslintPath?: string;
  /** Enable ESLint autofix feature (modifies source files) */
  fix?: boolean;
  /** ESLint output formatter (string name or custom function) */
  formatter?: string | ((results: ESLintResult[]) => string);
}

Error and Warning Control

interface ErrorWarningOptions {
  /** Force emit errors regardless of ESLint result severity */
  emitError?: boolean;
  /** Force emit warnings regardless of ESLint result severity */
  emitWarning?: boolean;
  /** Fail module build if ESLint reports errors */
  failOnError?: boolean;
  /** Fail module build if ESLint reports warnings */
  failOnWarning?: boolean;
  /** Report errors only, suppress warnings */
  quiet?: boolean;
}

Output Reporting

interface OutputReportOptions {
  /** Write ESLint output to file for CI/reporting */
  outputReport?: boolean | {
    /** Output file path (relative to webpack output.path) */
    filePath: string;
    /** Custom formatter for report file */
    formatter?: string | ((results: ESLintResult[]) => string);
  };
}

Complete Options Interface

interface ESLintLoaderOptions extends ESLintIntegrationOptions, CacheOptions, ErrorWarningOptions, OutputReportOptions {
  // All ESLint CLIEngine options are also supported:
  // configFile, baseConfig, rules, globals, extensions, etc.
}

Option Validation Schema

All options are validated against a JSON schema during loader initialization:

interface OptionsSchema {
  /** Cache configuration - boolean or directory path string */
  cache?: boolean | string;
  /** Path to ESLint package - defaults to 'eslint' */
  eslintPath?: string;
  /** Formatter function or name - defaults to 'stylish' */
  formatter?: string | ((results: ESLintResult[]) => string);
  /** Enable ESLint autofix feature */
  fix?: boolean;
  /** Always emit webpack errors regardless of ESLint severity */
  emitError?: boolean;
  /** Always emit webpack warnings regardless of ESLint severity */
  emitWarning?: boolean;
  /** Fail webpack build on ESLint errors */
  failOnError?: boolean;
  /** Fail webpack build on ESLint warnings */
  failOnWarning?: boolean;
  /** Suppress warnings, show errors only */
  quiet?: boolean;
  /** Report output configuration */
  outputReport?: boolean | {
    /** Output file path (relative to webpack output.path) */
    filePath: string;
    /** Custom formatter for report file */
    formatter?: string | ((results: ESLintResult[]) => string);
  };
}

Default Values:

  • eslintPath: 'eslint'
  • formatter: 'stylish' (ESLint's default formatter)
  • cache: false
  • fix: false
  • All boolean options: false

Validation Rules:

  • cache: Must be boolean or non-empty string
  • eslintPath: Must be string (validated at runtime for valid ESLint package)
  • formatter: String name or function (validated against ESLint's available formatters)
  • outputReport.filePath: Required when outputReport is object
  • Boolean options: Strict boolean validation (no truthy/falsy values)

Types

ESLint Result Types

interface ESLintResult {
  /** Absolute path to the linted file */
  filePath: string;
  /** Array of lint messages (errors/warnings) */
  messages: ESLintMessage[];
  /** Total number of error-level messages */
  errorCount: number;
  /** Total number of warning-level messages */
  warningCount: number;
  /** Number of errors that can be automatically fixed */
  fixableErrorCount: number;
  /** Number of warnings that can be automatically fixed */
  fixableWarningCount: number;
  /** Fixed source code if autofix was applied */
  output?: string;
  /** Original source code */
  src?: string;
}

interface ESLintMessage {
  /** ESLint rule that triggered this message */
  ruleId: string;
  /** Message severity: 1 = warning, 2 = error */
  severity: 1 | 2;
  /** Human-readable description of the issue */
  message: string;
  /** Line number where issue occurs (1-based) */
  line: number;
  /** Column number where issue occurs (1-based) */
  column: number;
  /** AST node type that triggered the rule */
  nodeType: string;
  /** Source code excerpt where issue occurs */
  source: string;
  /** Autofix information if available */
  fix?: ESLintFix;
}

interface ESLintFix {
  /** Character range to replace [start, end] */
  range: [number, number];
  /** Replacement text for the range */
  text: string;
}

Webpack Loader Types

interface LoaderContext {
  /** Webpack loader context with emit methods */
  emitError: (error: Error) => void;
  emitWarning: (warning: Error) => void;
  /** Make loader result cacheable */
  cacheable: () => void;
  /** Async callback for returning results */
  async: () => (error?: Error, content?: string, map?: Object) => void;
  /** Absolute path to current resource being processed */
  resourcePath: string;
  /** Webpack compiler instance */
  _compiler: {
    options: {
      output: {
        path: string;
      };
    };
  };
}

Internal Component Types

interface EngineResult {
  /** ESLint CLIEngine constructor */
  CLIEngine: typeof import('eslint').CLIEngine;
  /** Cached ESLint engine instance */
  engine: import('eslint').CLIEngine;
}

interface CacheParams {
  /** Cache directory path */
  cacheDirectory: string | boolean;
  /** Cache identifier for versioning */
  cacheIdentifier: string;
  /** Enable compression for cache files */
  cacheCompression: boolean;
  /** Loader options for cache key generation */
  options: ESLintLoaderOptions;
  /** Source code to cache */
  source: string;
  /** Transform function to generate cacheable result */
  transform: () => ESLintResult;
}

Common Usage Patterns

Development Mode with Hot Module Replacement

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          emitWarning: true, // Prevents HMR from breaking on lint errors
          cache: true
        }
      }
    ]
  }
};

Production Build with Strict Linting

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          failOnError: true,
          failOnWarning: true,
          cache: true
        }
      }
    ]
  }
};

CI/CD with Report Generation

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          cache: true,
          outputReport: {
            filePath: 'eslint-report.xml',
            formatter: 'checkstyle'
          }
        }
      }
    ]
  }
};

Custom ESLint Instance

// webpack.config.js
const path = require('path');

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          eslintPath: path.join(__dirname, 'custom-eslint-config'),
          formatter: require('eslint-friendly-formatter')
        }
      }
    ]
  }
};

Error Handling

The loader integrates with webpack's error handling system:

  • Lint Errors: Reported via loaderContext.emitError() (stops compilation by default)
  • Lint Warnings: Reported via loaderContext.emitWarning() (allows compilation to continue)
  • Configuration Errors: Thrown as exceptions that stop webpack compilation
  • ESLint Execution Errors: Caught and reported via appropriate emitter

The emitError and emitWarning options override the default behavior based on ESLint severity levels.

Migration Notes

This package is deprecated. For webpack 5 and newer ESLint versions, use eslint-webpack-plugin instead:

npm uninstall eslint-loader
npm install eslint-webpack-plugin --save-dev
// webpack.config.js
const ESLintPlugin = require('eslint-webpack-plugin');

module.exports = {
  plugins: [
    new ESLintPlugin({
      // options
    })
  ]
};