Package detail

gulp-eslint-new

origin-165kMIT2.4.0

A gulp plugin to lint code with ESLint 8 and 9.

gulpplugin, eslint, gulp, errors

readme

gulp-eslint-new · npm version

A gulp plugin to lint code with ESLint 8 and 9.

Installation

Make sure that you are using a version of Node.js supported by your version of ESLint. See prerequisites for ESLint 8 and ESLint 9. For TypeScript support, you need TypeScript 4.8 or later.

To install gulp-eslint-new, use npm:

npm i -D gulp-eslint-new

gulp-eslint-new will also install the latest version of ESLint 9, unless another one is found. To use a particular version of ESLint, install it by yourself. For example, to use ESLint 8.8.0:

npm i -D gulp-eslint-new eslint@8.8.0

Migrating

If you are migrating from gulp-eslint, you probably won't need to make any substantial changes to your gulp task, as the API is widely compatible. Note though that many options have changed: the current options are documented in the gulpESLintNew(options) section.

Also note that gulp-eslint-new is designed to work with ESLint 8 or 9, whereas the latest release of gulp-eslint only supports ESLint 6: you will need to update your project to address breaking changes in ESLint. You can follow the links below for more information.

Usage

const { src } = require('gulp');
const gulpESLintNew = require('gulp-eslint-new');

// Define the default gulp task.
exports.default =
() =>
src(['scripts/*.js'])                   // Read files.
.pipe(gulpESLintNew({ fix: true }))     // Lint files, create fixes.
.pipe(gulpESLintNew.fix())              // Fix files if necessary.
.pipe(gulpESLintNew.format())           // Output lint results to the console.
.pipe(gulpESLintNew.failAfterError());  // Exit with an error if problems are found.

Or use the plugin API to do things like:

// gulpfile.mjs
import js               from '@eslint/js';
import jquery           from 'eslint-plugin-jquery';
import globals          from 'globals';
import gulp             from 'gulp';
import gulpESLintNew    from 'gulp-eslint-new';

export default
() =>
gulp.src(['**/*.{js,mjs}', '!node_modules/**'])
.pipe
(
    gulpESLintNew
    (
        {
            configType:     'flat',
            overrideConfig:
            [
                js.configs.recommended,
                jquery.configs.slim,
                {
                    languageOptions:
                    {
                        globals:
                        {
                            ...globals.browser,
                            ...globals.jquery,
                            chrome: 'readonly',
                        },
                    },
                    rules:  { 'strict': 'error' },
                },
            ],
            plugins:        { jquery },
            warnIgnored:    true,
        },
    ),
)
.pipe(gulpESLintNew.formatEach('compact', process.stderr));

For additional examples, look through the example directory.

API

gulpESLintNew()

Run ESLint with default settings. A configuration file will be resolved depending on the version of ESLint used.

gulpESLintNew(options)

Param type: Record<string, unknown>

Run ESLint with the specified options. All supported options are listed below. See the linked content for details about each option.

General options

File enumeration options

Linting options

Autofix options

Reporting options

Other options

General Options

options.configType

Type: "eslintrc" | "flat" | null

ESLint supports two types of configuration: a new config type, aka flat config, based on file eslint.config.*, and a legacy config type, or eslintrc config, based on file .eslintrc.

In ESLint 8, the default config type is the legacy config, and the new config is partly supported depending on the version of ESLint used. To use the the new config with ESLint 8 in gulp-eslint-new, set the option configType to "flat".

ESLint 9 uses the new config type by default. To use the legacy config with ESLint 9 in gulp-eslint-new, set the option configType to "eslintrc".

The new and legacy config types differ significantly in the available options and their usage. Refer to the respective documentation in ESLint for the specifics of each options.

options.cwd

Type: string

The working directory. This must be an absolute path. Default is the current working directory.

The working directory is where ESLint will look for a .eslintignore file by default. It is also the base directory for any relative paths specified in the options (e.g. overrideConfigFile, resolvePluginsRelativeTo, rulePaths, overrideConfig.extends, etc.). The location of the files to be linted is not related to the working directory.

File Enumeration Options

options.ignore

Type: boolean

When false, ESLint will not respect .eslintignore files or ignore patterns in your configurations.

options.ignorePath

Type: string

The path to a file ESLint uses instead of .eslintignore in the current working directory. This option in not available when configType is "flat".

options.ignorePatterns

Type: string[] | null

Ignore file patterns to use in addition to config ignores. This option in only available when configType is "flat".

Autofix Options

options.fix

Type: boolean | (message: LintMessage) => boolean

Set to true or a function to generate fixes when possible, or set to false to explicitly disable autofixing. If a predicate function is present, it will be invoked once for each lint message, and only the lint messages for which the function returned true will be reported.

See the Autofix section for more information and examples.

options.fixTypes

Type: ("directive" | "problem" | "suggestion" | "layout")[] | null

The types of fixes to apply. Default is all types.

Reporting Options

options.quiet

Type: boolean

When true, this option will filter warning messages from ESLint results. This mimics the ESLint CLI --quiet option.

Type: (message: LintMessage, index: number, list: LintMessage[]) => unknown

When a function is provided, it will be used to filter ESLint result messages, removing any messages that do not return a true (or truthy) value.

options.warnIgnored

Type: boolean

When true, add a result warning when ESLint ignores a file. Default is false.

This can be used to find files that are needlessly being loaded by gulp.src. For example, since ESLint automatically ignores file paths inside a node_modules directory but gulp.src does not, a gulp task may take seconds longer just reading files from node_modules.

gulpESLintNew(overrideConfigFile)

Param type: string

Shorthand for defining options.overrideConfigFile.

gulpESLintNew.result(action)

Param type: (result: Object) => void

Call a function for each ESLint file result. No returned value is expected. If an error is thrown, it will be wrapped in a gulp PluginError and emitted from the stream.

gulp.src(['**/*.js', '!node_modules/**'])
.pipe(gulpESLintNew())
.pipe
(
    gulpESLintNew.result
    (
        result =>
        {
            // Called for each ESLint result.
            console.log(`ESLint result: ${result.filePath}`);
            console.log(`# Messages: ${result.messages.length}`);
            console.log
            (
                `# Warnings: ${result.warningCount} (${
                result.fixableWarningCount} fixable)`,
            );
            console.log
            (
                `# Errors: ${result.errorCount} (${
                result.fixableErrorCount} fixable, ${
                result.fatalErrorCount} fatal)`,
            );
        },
    ),
);

Param Type: (result: Object, callback: Function) => void

Call an asynchronous, Node-style callback-based function for each ESLint file result. The callback must be called for the stream to finish. If an error is passed to the callback, it will be wrapped in a gulp PluginError and emitted from the stream.

Param Type: (result: Object) => Promise<void>

Call an asynchronous, promise-based function for each ESLint file result. If the promise is rejected, the rejection reason will be wrapped in a gulp PluginError and emitted from the stream.

gulpESLintNew.results(action)

Param type: (results: Object[]) => void

Call a function once for all ESLint file results before a stream finishes. No returned value is expected. If an error is thrown, it will be wrapped in a gulp PluginError and emitted from the stream.

The results list has additional properties that indicate the number of messages of a certain kind.

errorCount number of errors
warningCount number of warnings
fixableErrorCount number of fixable errors
fixableWarningCount number of fixable warnings
fatalErrorCount number of fatal errors
gulp.src(['**/*.js', '!node_modules/**'])
.pipe(gulpESLintNew())
.pipe
(
    gulpESLintNew.results
    (
        results =>
        {
            // Called once for all ESLint results.
            console.log(`Total Results: ${results.length}`);
            console.log
            (
                `Total Warnings: ${results.warningCount} (${
                results.fixableWarningCount} fixable)`,
            );
            console.log
            (
                `Total Errors: ${results.errorCount} (${
                results.fixableErrorCount} fixable, ${
                results.fatalErrorCount} fatal)`,
            );
        },
    ),
);

Param type: (results: Object[], callback: Function) => void

Call an asynchronous, Node-style callback-based function once for all ESLint file results before a stream finishes. The callback must be called for the stream to finish. If an error is passed to the callback, it will be wrapped in a gulp PluginError and emitted from the stream.

Param type: (results: Object[]) => Promise<void>

Call an asynchronous, promise-based function once for all ESLint file results before a stream finishes. If the promise is rejected, the rejection reason will be wrapped in a gulp PluginError and emitted from the stream.

gulpESLintNew.failOnError()

Stop a task/stream if an ESLint error has been reported for any file.

// Cause the stream to stop (fail) without processing more files.
gulp.src(['**/*.js', '!node_modules/**'])
.pipe(gulpESLintNew())
.pipe(gulpESLintNew.failOnError());

gulpESLintNew.failAfterError()

Stop a task/stream if an ESLint error has been reported for any file, but wait for all of them to be processed first.

// Cause the stream to stop (fail) when the stream ends if any ESLint error(s)
// occurred.
gulp.src(['**/*.js', '!node_modules/**'])
.pipe(gulpESLintNew())
.pipe(gulpESLintNew.failAfterError());

gulpESLintNew.format(formatter, writer)

formatter param type: string | Object | Function | undefined

writer param type: NodeJS.WritableStream | Function | undefined

Format all linted files once. This should be used in the stream after piping through gulpESLintNew; otherwise, this will find no ESLint results to format.

The formatter argument determines the ESLint formatter used to format linting results. If a string is provided, a formatter module by that name or path will be resolved. The resolved formatter will be either one of the built-in ESLint formatters, or a formatter exported by a module with the specified path (located relative to the ESLint working directory), or a formatter exported by a package installed as a dependency (the prefix "eslint-formatter-" in the package name can be omitted). Instead of providing a string, it is also possible to specify a formatter object as resolved by the ESLint method loadFormatter, or a formatter function directly. If this argument is undefined, a modified version of the ESLint "stylish" formatter will be used.

// Use the default gulp-eslint-new formatter.
gulpESLintNew.format()

// Use the "html" ESLint formatter.
gulpESLintNew.format('html')

// Use "eslint-formatter-pretty" as a formatter (must be installed with `npm`).
// See https://www.npmjs.com/package/eslint-formatter-pretty.
gulpESLintNew.format('pretty')

The writer argument may be a writable stream, Function, or undefined. As a writable stream, the formatter output will be written to the stream. If undefined, the formatter output will be written to gulp's log. A Function will be called with the formatter output as the only parameter.

// write to gulp's log (default)
gulpESLintNew.format()

// write messages to stdout
gulpESLintNew.format('junit', process.stdout)

gulpESLintNew.formatEach(formatter, writer)

formatter param type: string | Object | Function | undefined

writer param type: NodeJS.WritableStream | Function | undefined

Format each linted file individually. This should be used in the stream after piping through gulpESLintNew; otherwise, this will find no ESLint results to format.

The arguments for gulpESLintNew.formatEach are the same as the arguments for gulpESLintNew.format.

gulpESLintNew.fix()

Overwrite files with the fixed content provided by ESLint. This should be used in conjunction with the option fix in gulpESLintNew(options). Files without a fix and files that were not processed by ESLint will be left untouched.

See the Autofix section for more information and examples.

Autofix

ESLint can fix some lint problems automatically: this function is called autofix.

To enable autofix with gulp-eslint-new, set the option fix to true in gulpESLintNew(options), then pipe the stream to gulpESLintNew.fix(), e.g.

gulp.src(['**/*.{js,ts}', '!node_modules/**'])
.pipe(gulpESLintNew({ fix: true }))
.pipe(gulpESLintNew.fix());

See also the autofix examples.

The fix option applies fixes to the gulp stream. gulpESLintNew.fix() saves the fixed content to file. Rules that are fixable can be found in ESLint's rules list. When fixes are applied, a fixed property is set to true on the fixed file's ESLint result.

Custom Extensions

ESLint results are attached as an eslint property to the Vinyl files that pass through a gulp stream pipeline. This is available to streams that follow the initial gulp-eslint-new stream. The functions gulpESLintNew.result and gulpESLintNew.results are made available to support extensions and custom handling of ESLint results.

changelog

2.4.0 (2024-10-28)

  • TypeScript < 4.8 is no longer supported.
  • Improved TypeScript type declarations.

2.3.0 (2024-08-24)

  • Redefined TypeScript typings on the basis of @types/eslint 9.
  • Added main field to package.json file to support legacy tools.

2.2.0 (2024-07-08)

  • Updated TypeScript type declarations for ESLint 9 compatibility.
  • Added support for option flags, new in ESLint 9.6.
  • Improved readme file.

2.1.0 (2024-06-09)

  • Fixed and updated warning messages for ignored files.
  • Updated code examples and documentation.

2.0.0 (2024-04-06)

First release of gulp-eslint-new 2 supporting both ESLint 8 and 9.

  • Added support for ESLint 9.
  • Legacy options are no longer converted into the new format.
  • TypeScript < 4.6 is no longer supported.
  • Reorganized code examples to make them work with both ESLint 8 and 9.

1.9.1 (2024-02-11)

  • Fixed the type of the option quiet in the readme file.
  • Clarified that the option reportUnusedDisableDirectives is unsupported with flat config.
  • Updated code examples.

1.9.0 (2023-12-16)

  • The top level option reportUnusedDisableDirectives is no longer supported with flat config, as it was removed in ESLint 8.56.
  • Updated code examples.

1.8.4 (2023-10-02)

  • Fixed default setting and normalization of the option cwd with flat config.
  • Clarified that the option warnIgnored defaults to false.

1.8.3 (2023-07-30)

  • Using export = syntax in TypeScript type declaration file to enable type hinting in editors.

1.8.2 (2023-07-05)

  • Consolidated errors thrown when invalind options are passed to gulpESLintNew:
    • Updated error messages to clarify that undefined is a valid value for the options quiet, warnIgnored and warnFileIgnored.
    • Removed property code from the error thrown when an invalid value is specified for the option configType.
  • Improved TypeScript type declarations.

1.8.1 (2023-06-18)

  • Added validation for the legacy option warnFileIgnored.
  • gulp-eslint-new will now normalize cwd directories like ESLint 8.43.
  • overrideConfig validation is deferred to ESLint.

1.8.0 (2023-05-20)

  • Added validation for the options quiet and warnIgnored.
  • The miniumum supported TypeScript version is now 4.2.
  • Fixed and updated ignored file messages.
  • Improved TypeScript type declarations.
  • Improved readme file.

1.7.2 (2023-02-11)

  • Improved TypeScript type declarations for the flat configuration system.
  • Improved readme file.

1.7.1 (2022-12-02)

  • Fixed "premature close" error when piping into a failAfterError stream from a fix stream.
  • Removed useless text domainEmitter [object Object] from gulp error output.
  • Fixed a code example.

1.7.0 (2022-11-01)

  • Added support for the flat configuration system.
  • The format method of a LoadedFormatter object is now passed a second argument, as in ESLint 8.25 or later.
  • If option cwd is not specified, then cwd will be set to the current directory in the ESLint constructor options. This should avoid unexpected inconsistencies between ESLint and gulp-eslint-new in determining the current directory.
  • Updated TypeScript type declarations.
  • Updated examples and documentation.

1.6.0 (2022-09-12)

  • Improved performance by lazy loading all dependencies.
  • Allowing older versions of package @types/node (for Node.js < 18).
  • Printing a warning when legacy options are migrated.
  • Printing a warning when the function fix is used without the option fix.
  • Updated documentation.

1.5.1 (2022-06-14)

  • If ESLint ≥ 8.8 is used, ESLint results produced by ignored files now include the property suppressedMessages.

1.5.0 (2022-06-07)

  • Using the modified stylish formatter by default. If any fixable problems are found, the modified stylish formatter will output a link with instructions about the autofix function, instead of proposing the CLI option --fix.
  • Formalized support for any version of ESLint 8.
  • Transferred project to Origin₁.
  • Improved readme file.

1.4.4 (2022-05-19)

  • Fixed a regression in version 1.4.3 that caused a TypeError when gulpESLintNew was called with a string argument.
  • Minimal change in the readme file.

1.4.3 (2022-05-18)

  • When a dependency throws an error during an asynchronous stream operation, the emitted PluginError now includes the stack trace when printed.
  • Improved TypeScript type declarations.
  • Clarified code examples in the readme file.

1.4.2 (2022-02-27)

  • Added type definition for function fix.
  • Updated TSDoc.

1.4.1 (2022-02-26)

  • Fixed type inference for the arguments of callbacks provided to the functions result and results.

1.4.0 (2022-02-13)

  • Added support for legacy option extends.
  • Simplified and completed documentation of legacy options.
  • formatEach now uses one formatter per instance of ESLint.
  • Improved TypeScript type declarations.
  • Normalized markdown of readme file and changelog.

1.3.0 (2022-02-05)

  • Added support for new argument types to the functions format and formatEach:
    • formatter can now be a formatter object as resolved by the ESLint method loadFormatter.
    • writer can now be an async function.
  • Improved TypeScript type declarations.
  • Clarified the documentation.

1.2.0 (2022-01-29)

  • New function fix.
  • All functions exported by gulp-eslint-new are now available as named exports when gulp-eslint-new is imported with the import keyword (statically or dynamically).
  • When the option quiet is used, ESLint results now include the properties usedDeprecatedRules and (for ESLint ≥ 8.8) suppressedMessages.
  • The functions result and results now throw a TypeError when called with an invalid argument.
  • Updated examples and documentation.

1.1.2 (2022-01-15)

  • Formatting streams with ignored files no longer throws an exception when the option warnIgnored is used.
  • Added migration instructions to the readme file.
  • Updated examples.

1.1.1 (2022-01-08)

  • Changed installation instructions so that gulp-eslint-new gets added to the devDependencies.
  • Fixed a typo in an error message.

1.1.0 (2021-12-06)

1.0.0 (2021-11-14)

  • Using the new ESLint formatter API.
  • Added TypeScript type declarations.
  • result and results streams now support async functions as handlers.
  • Updated examples and documentation.
  • Added package.json to package exports.
  • Fix: format and results streams now stay open until the end of asynchronous operations in all supported versions of Node.js.

0.6.0 (2021-11-06)

  • Using ESLint 8.2.
  • Results lists have now the same "Count" properties of a single result: fixableErrorCount, fixableWarningCount and fatalErrorCount, in addition to the previously featured errorCount and warningCount.

0.5.1 (2021-11-04)

  • Unuseful ESLint options are now rejected: errorOnUnmatchedPattern, extensions, globInputPaths and cache-related ones.
  • Errors and warnings generated by gulp-eslint-new are now more similar to those generated by ESLint 8.
  • Updated examples and documentation.

0.5.0 (2021-10-27)

  • Using ESLint 8.1.
  • Updated documentation.

0.4.0 (2021-10-10)

  • Using ESLint 8.
  • Changed plugin name to gulp-eslint-new.

0.3.2 (2021-09-11)

  • Updated dependencies in prospect of ESLint 8.

0.3.1 (2021-05-03)

  • Updated readme file.

0.3.0 (2020-07-03)

  • Fixed plugins option handling to accept both an array (old API) or a map-like object (new API).

0.2.1 (2020-06-30)

  • Minor optimizations.
  • Showing npm badge in the readme file.

0.2.0 (2020-06-27)

0.1.0 (2020-06-22)

Initial release derived from gulp-eslint.

  • Using ESLint 7.
  • Disambiguated plugin name to gulp-eslint7.

For the changelog of gulp-eslint until forking, see here.