GithubHelp home page GithubHelp logo

grunt-eslint's Introduction

grunt-eslint

Validate files with ESLint

Install

npm install --save-dev grunt-eslint

Usage

require('load-grunt-tasks')(grunt);

grunt.initConfig({
	eslint: {
		target: ['file.js']
	}
});

grunt.registerTask('default', ['eslint']);

Examples

Custom config and rules

grunt.initConfig({
	eslint: {
		options: {
			overrideConfigFile: 'conf/eslint.json',
			rulePaths: ['conf/rules']
		},
		target: ['file.js']
	}
});

Custom formatter

grunt.initConfig({
	eslint: {
		options: {
			format: require('eslint-tap')
		},
		target: ['file.js']
	}
});

Options

See the ESLint options.

In addition the following options are supported:

format

Type: string
Default: 'stylish'

The name of a built-in formatter or path to a custom one.

Some formatters you might find useful: eslint-json, eslint-tap.

outputFile

Type: string
Default: ''

Output the report to a file.

quiet

Type: boolean
Default: false

Report errors only.

maxWarnings

Type: number
Default: -1 (Means no limit)

The nmber of warnings to trigger non-zero exit code.

failOnError

Type: boolean
Default: true

Fail the build if ESLint found any errors.

grunt-eslint's People

Contributors

a-laughlin avatar christianmurphy avatar dylang avatar enure avatar ex1st avatar gkz avatar holgerjeromin avatar iudelsmann avatar jraller avatar jsturgis avatar le0pard avatar makotot avatar manicki avatar matz3 avatar mightyiam avatar mohayonao avatar ntwb avatar okuryu avatar oliviertassinari avatar papandreou avatar petersendidit avatar richienb avatar samverschueren avatar shospodarets avatar sindresorhus avatar toddjordan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-eslint's Issues

Should grunt-eslint 1.2.0 have been 2.0.0?

Thanks for keeping the package up to date! However, the recent #35 broke my build. I think the major version number in grunt-eslint should be incremented when the ESLint dependency is updated and the ESLint version brings in new default rules.

More precisely: I have a project (https://github.com/zerovm/swift-browser/) which has a dependency on grunt-eslint version ^1.1.0. When 1.2.0 was released with the updated dependency on ESLint, Travis began using it — and my build failed. (Fixing the build was not difficult, it was merely surprising to see a build failure unrelated to the feature I was working on.)

So while the public API was kept the same, one could argue that grunt-eslint 1.2.0 isn't really "compatible" with version 1.1.0. Hence, I suggest incrementing the major version number.

force switch needed

Hi @sindresorhus,

Would it be possible to ad force switch as grunt-contrib-jshint has? I need to report all errors in a file but not fail the task itself.

Thanks,
Filip

Support multiple targets

It would be great to be able to have multiple eslint targets, like this:

eslint: {
    standard: {
        options: {
            configFile: "bower_components/eslintconfigs/standard.json"
        },
        target: [
            "Gruntfile.js",
            "src/**/*.js",
            "!src/**/nls/**/*.js"
        ]
    },
    tests: {
        options: {
            configFile: "bower_components/eslintconfigs/jasmine.json"
        },
        target: ["tests/**/*.js"]
    },
    nls: {
        options: {
            configFile: "bower_components/eslintconfigs/legacy-nls.json"
        },
        target: ["src/**/nls/**/*.js"]
    }
}

Currently if you try to do this, grunt knows what you mean but grunt-eslint doesn't:

image

For example, grunt-csslint has the functionality.

(Am aware I could achieve the desired outcome by adding .eslintc files to the various directories, but this setup would work a lot better in many cases, especially where we have a master set of configs being used for dozens of projects and pulled in via Bower or Maven.)

Happy to do a PR, but wanted to check if there were reasons not to do it first.

.eslintignore support

ESLint has, just like JSHint, config file for excluding specific files from linting. It would be nice (for consistency sake) to have this implemented. That way, other environments such as text editor plugins which can pickup those files and linters via build tools have same entry point when deciding which files to exclude (as opposed to defining those file in globbing pattern in Gruntfile).

Switch to CLIEngine

http://eslint.org/blog/2014/09/eslint-0.8.0-released/

ESLint now exports the CLIEngine interface, which is what powers the ESLint command line utility. If you are writing plugins for other systems that make use of the ESLint cli object, then you should transition to using CLIEngine instead.

The cli object will stop being exported in a future version of ESLint.

Don't treat warnings as errors

ESLint has a concept of warnings (identified by 1) apart from ignoring the rule (0) and erroring on breaking it (2). grunt-eslint shouldn't error on warnings.

Different output between `eslint` and `grunt eslint`

I have an invalid .eslintrc rule, apparently, which I found out by running $ eslint . on the command line:

$ eslint --version # v0.23.0
$ eslint .

/Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/config-validator.js:88
        throw new Error(message.join(""));
              ^
Error: /Users/pdehaan/dev/fxa-content-server_pd/fxa-content-server/.eslintrc:
    Configuration for rule "no-use-before-define" is invalid:
    Value "true" is the wrong type.

    at validateRuleOptions (/Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/config-validator.js:88:15)
    at /Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/config-validator.js:101:13
    at Array.forEach (native)
    at Object.validate (/Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/config-validator.js:100:35)
    at loadConfig (/Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/config.js:99:19)
    at getLocalConfig (/Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/config.js:225:23)
    at Config.getConfig (/Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/config.js:363:22)
    at processText (/Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/cli-engine.js:183:27)
    at processFile (/Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/cli-engine.js:226:12)
    at /Users/pdehaan/.npm-packages/lib/node_modules/eslint/lib/cli-engine.js:322:26

Where my .eslintrc file has the following:

$ cat .eslintrc
{
  "env": {
    "amd": true,
    "es6": true,
    "mocha": true,
    "node": true
  },
  "rules": {
    ...
    "no-use-before-define": true,
    "no-with": 2,
    ...
  }
}

NOTE: eslint is complaining about that "no-use-before-define": true rule, since that true should be a 0, 1, or 2.

BUT, this gets interesting when I run grunt eslint, which tells me everything is fine.

$ cat package.json | grep "eslint"
    "grunt-eslint": "14.0.0",
$ ./node_modules/grunt-eslint/node_modules/.bin/eslint --version
v0.22.1

$ grunt eslint
Running "eslint:grunt" (eslint) task


Running "eslint:app" (eslint) task


Running "eslint:tests" (eslint) task


Running "eslint:scripts" (eslint) task


Running "eslint:server" (eslint) task


Done, without errors.


Execution Time (2015-06-16 18:03:21 UTC)
loading tasks   2.2s  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 22%
eslint:grunt   481ms  ▇▇▇▇▇ 5%
eslint:app        6s  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 60%
eslint:tests      1s  ▇▇▇▇▇▇▇▇▇▇ 10%
eslint:server  325ms  ▇▇▇▇ 3%
Total 10.1s

Not sure why $ eslint . fails hard on invalid .eslintrc rules, but grunt eslint replies with "Done, without errors."

Configuration issues aren't caught

This is semi-related to eslint/eslint#1443

If you have an error in your eslintrc file, the call to CLIEngine executeOnFiles throws an exception. Under my (relatively stock standard?) environment, the grunt task doesn't finish, but returns a "Done, without errors." message. Something like:

        try {
        var report = engine.executeOnFiles(this.filesSrc);
    } catch (e) {
        grunt.warn(e);

Catches the error and lets the caller know that something messed up.

"env" vs "envs"

The API eslint exposes is not identical to the command line API or however it parses .eslintrc configs. In order to get the env option to work you must instead use envs and pass an array instead of an object literal.

What's documented at eslint.org:

{
    'env' : {
        'browser' : true,
        'node' : true
    }
}

What's required using grunt-eslint:

{
    'env' : [
        'browser',
        'node'
    ]
}

For some context, I asked and apparently eslint used to support both env and envs. It seems like a bug - or just poor design - on their end, but at the very least we should document this in the README.

Linting ignored files triggers a warning

See eslint/eslint#905 for the description of the problem & discussion around it.

Basically, if you want to have filest passed to the eslint task usable for usage with grunt-newer, you need to pass files, not directories. But if you pass files and some of them are in .eslintignore, ESLint triggers a warning. This can seriously flood the console with warnings not applicable here; it's enough to e.g. pass app/**/*.js to the eslint task and have app/vendor/** in .eslintignore.

@nzakas proposed to add the --silent option to ignore warnings which would make this issue disappear but would also make all other warnings disappear.

Do you have a better idea how to solve this problem? Input welcome!

Dynamic altering `target` does not affected linted files

I am using grunt-eslint along with grunt-contrib-watch and I have the following snippet in my Gruntfile.js:

    grunt.event.on('watch', function(action, filepath) {
        grunt.config('eslint.target', filepath);
    });

In order to lint only files altered and not all the project. Unfortunately it does not seem to work for grunt-eslint and the eslint lints all project.

grunt eslint does nothing

It just sits indefinitely without any output until I ctrl+c the command.

How can I troubleshoot this?

"quiet" option does not work anymore

Since this task is using the CLIEngine, the "quiet" option has not effect anymore.
Would be great if this task filters out the warnings like the CLI in eslint does.

I can also provide a PR if welcome.

callback null error

I think a bug was introduced recently. Sometimes the array of callbacks referenced on line 77 in handle-callback-err.js is empty which causes an error when trying to set the handled property on the last callback.

Update to eslint 0.6.*

as said in the subject, eslint has been updated to version 0.6.1, which supports quite a lot of new rules

Updating package.json should be sufficient - seems to be working fine for me

envs doesn't work correctly

I'm trying to set up ESLint from my Grunt setup, so that when I lint all of my main code it uses a particular config file, and when I lint my test code it does exactly the same but adds the 'mocha' environment.

The way to do this with eslint itself is easy - you just add '--env mocha' to the command line and everything else just works.

The grunt-eslint documentation seems to imply that I can do this by adding

envs: ['mocha']

to the options for this step. This doesn't work however.

I think the problem is that the file tasks/lib/eslint.js doesn't handle this setting properly. Adding this to that file seems to make it work, but I'm not sure if there's just another way that it's handled?

    if (options.envs) {
      args.push("--env", options.envs.join(","));
    }

Warning: Object.keys called on non-object

Here is my eslint configuration:

eslint: {
  target: ["Gruntfile.js", "test/**/*.js", "scripts/**/*.js"]
}

When i got this warning, the linter doesn't show the file.
When i define the target just to "Gruntfile.js" where I do not call Object.keys, the warning appears anyway.
Setting options to an empty object was not the solution.
I tried to flag with "--verbose" and "--debugger" as well but got no errors in console.

Got version 5.1.0

Formatter not working

Hi, I'm not seeing any changes when I switch the format in the options property, also the default, stylish doesn't look right either.

Is there something else I need to do to make this work?

Version 0.6.0 Doesn't support eslint globals config?

Version 0.6.0 Doesn't support eslint globals config?
It works well with version 0.5.0, But after upgrading to v0.6.0 I got lots of 'no-undef' error, Actually they have been enabled in globals config.
Anything wrong?

different

Is it possible to set different rules for each set of files? For example a set of rules for node, then for browser js etc. I've tried this:

    eslint: {
        node: {
            options: {
                envs: ['node'],
                rules: {
                    quotes: [0, 'double'],
                    strict: 0
                }
            },
            target: [
                'src/app.js'
            ]
        },
        browser: {
            options: {
                envs: ['browser'],
                rules: {
                  .....
                }
            },
            target: [
                 .....
            ]                
        }
    }

But it doesn't find files to validate.

Allow specifying custom config file (or object)

Currently, it seems grunt-eslint always uses the default eslint settings.

It would be useful to have a way to specify a custom configuration object, or point to a local .jshintrc file (or maybe use .jshintrc in the same folder as the Gruntfile.js by default if it’s available?

Show CLI output on successful run

Maybe like grunt-contrib-jshint does it:

Running "jshint:src" (jshint) task

5 files lint free.

I'll see if I can make a PR, unless someone beats me to it.

Allow specifying different sets of options

I'd like to be able to specify one set of rules for my browser JS files and another for my Node JS files.

Basically, I'd like this to work:

initConfig = {
  eslint: {
    options: { config: 'conf/general-eslint.json' },
    browser_stuff: {
      options: { config: 'conf/browser-specific-eslint.json' },
      target: grunt.file.expand(['js/*.js']),
    },
    node_stuff: {
      options: { config: 'conf/node-specific-eslint.json' },
      target: ['Gruntfile.js']
    }
  }
};

As a general note, you should consider making the grunt-eslint very similar to the grunt-contrib-jshint API. A few things missing:

  • My suggestion above
  • Set options as an object rather than a file path
  • Automatically glob file names (i.e. grunt.file.expand)

Show the total number of linted files

grunt-contrib-jshint:

$ grunt jshint
Running "jshint:all" (jshint) task
>> 185 files lint free.

Done, without errors.

grunt-eslint:

$ grunt eslint
Running "eslint:all" (eslint) task

Done, without errors.

Having such information is important; sometimes a misconfiguration makes the tool omit most files and seeing a much smaller number than anticipated would ring a bell.

Version history and changelog

Could not find any info other than checking commits, about the history between versions and what had changed.

Please add version history and short changelog.

Run on directory

How do I run grunt eslint check on a directory?
For eslint I can specify a directory as target, however I can't get it to work here.
I have tried the following, but they all result in an error:

eslint: {
    options: {
        outputFile: "errors.txt"
    },
    a: ["path/to/source/"],
    b: ["path/to/source/*.js"],
    c: ["path/to/source/**/*.js"],
    c: ["path/to/source/{}.js"],
    d: {
        cwd: "path/to/source",
        prefix: "path/to/source",
        src: [
            "**/*.js"
        ]
    }
}

Ability to set custom rules in Gruntfile

Currently I have the following npm script in my package.json file:

  "scripts": {
    "jsdoc-lint": "eslint loop --rule 'valid-jsdoc: [1, {requireReturn: false, requireParamDescription: false}]'"
  }

I can't figure out if there is an easy way to do something similar w/ grunt-eslint (without resorting to a separate config file.

I thought it would be convenient if I could do something like:

  "eslint": {
    "app": {
      "src": "<%= APP.CODE_DIRS %>*.js"
    },
    "jsdoc": {
        "options": {
          "rules": {
            "valid-jsdoc": [1, {"requireReturn": false, "requireParamDescription": false}]
          }
        },
        "src": "<%= eslint.app.src %>"
    }
  }

Then I can lint the syntax using grunt eslint:app or just lint the JSDoc validity using grunt eslint:jsdoc.

Support command line option "format"

I'm not sure what the grunt plugin convention (for passing through options) is but for the following line I would expect that the plugin uses the tap format.

$ grunt eslint --format=tap

My use case is a remote-controlled Gruntfile, so changing the Gruntfile itself is unfortunately no option.

This is hacky workaround for tasks/eslint.js:

...
  grunt.registerMultiTask('eslint', 'Validate files with ESLint', function () {
      var opts = this.options({
        outputFile: false,
        quiet: false
      });

      // new code
      if (grunt.option('format')) {
        opts.format = grunt.option('format');
      }

      ...

opts.outputFile feedback

Hi,

Thanks for the great plugin! I have one small issue, I miss feedback if you use an outputFile.

I made a quick fix by adding this function:

function getErrorsAndWarnings(results, outputFile) {
    var errors = [],
        warnings = [];

    results.some(function (result) {
        result.messages.some(function (message) {
            if(message.severity === 2) {
                errors.push(message);
            } else if(message.severity === 1) {
                warnings.push(message);
            }
        });
    });

    if(warnings.length > 0 || errors.length > 0) {
        return chalk.yellow('eslint: Wrote ' + errors.length + ' errors and ' + warnings.length + ' warnings to ' + outputFile + '.');
    } else {
        return chalk.green('eslint: success without errors.');
    }
}

and then ofcourse adding the call grunt.log.writeln(getErrorsAndWarnings(results, opts.outputFile)); within if (opts.outputFile) {

I can add a pull request if needed.

Semver compliance

Can you stick to semver for versioning? For example updating the eslint dependency from 0.23.0 -> 0.24.0 is not a breaking change, should be a patch number increment 15.0.1 not 16.0.0

Thanks

Options for disabling all rules by default

Hello.
First, thanks for this great plugin.

This issue could be labelled as a question.
I'm wondering if adding an option to reset all rules could be a good idea ?

Eslint has the --reset cli option for this use-case.

Regards.

Report output to a file

Would it be possible to add a configuration option to specify a log file in which the report output is saved?

Allow formatter output to be written to file

The following option
-o
This option specifies the output file name which can be passes for the output of the task to be put into

Example:

eslint -o ./test/test.html
When specified, the given format is output into the provided file name.

Support for 1.0.0

Hi there,

ESLint 1.0.0 was just released.
Are you going to update grunt-eslint to support it?

Greet

target files doesn't expand

Thanks for the task man, I am having an issue here..

This works:

  grunt.config('eslint', {
    target: ['file.js']
  });

But this doesn't:

  grunt.config('eslint', {
    target: ['src/**/*.js']
  });

Using eslint cli, you can actually do this eslint src/**/*.js

Looking at the task code, it may be more compliant to use this.files grunt api

any suggestion?

Multiple configuration / targets

Hello, this is more a question rather than an issue. Is it possible to run eslint in multiple targets with different config?

Something like this:

eslint: {
   source: {target: ['src/*.js'], envs: ['node']},
   tests: {target: ['tests/*.js'], envs: ['node', 'mocha']},
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.