在Grunt中为单个文件运行JSHint

问题描述 投票:5回答:2

我在Grunt中有多个子任务(src,lib和test)的JSHint设置,效果很好。但是,由于我们刚开始使用此设置,因此我们的许多源文件中存在许多错误。

$ grunt jshint:src
... lots of errors ...

在一次处理一个文件的同时,是否可以重新打印该单个文件?

$ grunt jshint:src:one.js
... only errors from one.js ...

更新

一个复杂因素是监视任务还有多个子任务,可根据编辑的文件类型触发不同的任务。

watch: {
    src: {
        files: [ SRC_DIR + "hgm*.js" ],
        tasks: [ "jshint:src", "test" ]
    },
    lib: {
        files: [ "lib/hgm-test-setup.js", "lib/hgm.loader.js" ],
        tasks: [ "jshint:lib", "test" ]
    },
    test: {
        files: [ "tests/**/*.js" ],
        tasks: [ "jshint:test", "test" ]
    }
}

原因是srclib使用一个.jshinttest使用另一个指定用于测试的所有全局变量如断言。我可以结合srclib,但我可以覆盖test的JSHint配置文件吗?

gruntjs jshint
2个回答
4
投票

grunt-contrib-watch-task提供了一个如何配置任务的示例,并使用watch-event仅对已更改的文件进行linting:

grunt.initConfig({
  watch: {
    scripts: {
      files: ['lib/*.js'],
      tasks: ['jshint'],
      options: {
        nospawn: true,
      },
    },
  },
  jshint: {
    all: ['lib/*.js'],
  },
});

// on watch events configure jshint:all to only run on changed file
grunt.event.on('watch', function(action, filepath) {
  grunt.config(['jshint', 'all'], filepath);
});

0
投票

由于上面的答案并不是我所期待或正在寻找的,我想提供这个答案......

你可以像grunt jshint-file:src/filename.js一样调用它

grunt.registerTask('jshint-file',
        'Runs jshint on a file',
        function (filePath) {
            var reportFunc = require('jshint/src/reporters/unix').reporter
            var optionsString = grunt.file.read('.jshintrc')
            var options = JSON.parse(optionsString)
            jshint(grunt.file.read(filePath), options)
            errors = jshint.data().errors.map(function (error) {
                var record = {};
                record.file = filePath;
                record.error = error;
                return record;
            });
            console.log(reportFunc(errors))
        }
    )
© www.soinside.com 2019 - 2024. All rights reserved.