冠军

导航

Grunt 之 使用 JavaScript 语法检查工具 jshint

前端开发环境准备好了,我们准备开始进行开发。

前端开发的主力语言是 JavaScript,这是一种脚本语言,没有编译器,也就没有了编译器带给我们的语法检查,怎样保证代码的质量呢?jshint 是一个强大的工具。

1. 概要说明

 

官方地址:http://jshint.com/

GitHub 地址:https://github.com/jshint/jshint

JSHint 是一个使用 JavaScript 编写的 JavaScript 的代码质量检查工具,主要用来检查代码质量以及找出一些潜在的代码缺陷。

2. 下载 jshint

使用 NPM 下载一个 jshint 让我们测试一下。

npm install grunt-contrib-jshint --save-dev

看到如下的输出

PS C:\Study\framework> npm install grunt-contrib-jshint --save-dev
npm WARN peerDependencies The peer dependency grunt@>=0.4.0 included from grunt-contrib-jshint will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.
grunt@0.4.5 node_modules\grunt
├── dateformat@1.0.2-1.2.3
├── which@1.0.9
├── eventemitter2@0.4.14
├── getobject@0.1.0
├── colors@0.6.2
├── rimraf@2.2.8
├── async@0.1.22
├── hooker@0.2.3
├── grunt-legacy-util@0.2.0
├── exit@0.1.2
├── minimatch@0.2.14 (sigmund@1.0.1, lru-cache@2.6.5)
├── lodash@0.9.2
├── coffee-script@1.3.3
├── underscore.string@2.2.1
├── iconv-lite@0.2.11
├── nopt@1.0.10 (abbrev@1.0.7)
├── findup-sync@0.1.3 (glob@3.2.11, lodash@2.4.2)
├── grunt-legacy-log@0.1.2 (grunt-legacy-log-utils@0.1.1, lodash@2.4.2, underscore.string@2.3.3)
├── glob@3.1.21 (inherits@1.0.2, graceful-fs@1.2.3)
└── js-yaml@2.0.5 (esprima@1.0.4, argparse@0.1.16)

grunt-contrib-jshint@0.11.2 node_modules\grunt-contrib-jshint
├── hooker@0.2.3
└── jshint@2.8.0 (strip-json-comments@1.0.4, exit@0.1.2, shelljs@0.3.0, console-browserify@1.1.0, minimatch@2.0.10, cli@
0.6.6, lodash@3.7.0, htmlparser2@3.8.3)

重新查看 package.json ,可以看到已经添加了 jshint 的依赖说明。

{
  "name": "framework",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "grunt": "^0.4.5",
    "grunt-contrib-jshint": "^0.11.2"
  },
  "devDependencies": {
    "grunt-contrib-jshint": "^0.11.2"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

3. 在 grunt 中配置 jshint 测试 javascrpt 脚本

在我们的项目文件夹根目录中,创建一个前端项目源码的文件夹 app,在其中创建一个 scripts 的文件夹,用来保存我们编写的脚本。

创建名为 app.js 的脚本文件,写入如下内容。

// Hello.
//
// This is JSHint, a tool that helps to detect errors and potential
// problems in your JavaScript code.
//
// To start, simply enter some JavaScript anywhere on this page. Your
// report will appear on the right side.
//
// Additionally, you can toggle specific options in the Configure
// menu.

function main() {
  return 'Hello, World!';
}

main();

我们需要在 grunt 中配置 jshint 的任务。

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),

    // Make sure code styles are up to par and there are no obvious mistakes
    // code style check
    // 代码检查
    jshint: {
        all: [
            'app/**/*.js'
             ],
        options: {
            browser: true,            // browser environment
            devel: true                // 
            }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
};

all 中配置需要检查的脚本文件路径,options 中的 browser 用来配置说,我们的脚本需要在浏览器环境下执行,这样,我们的脚本中可以使用 console、setTimeout 等等函数了。

现在执行 grunt hint 就可以看到如下的输出。

PS C:\Study\framework> grunt jshint
Running "jshint:all" (jshint) task
>> 1 file lint free.

Done, without errors.

如果把脚本中 main() 后面的分号 (;) 删除掉,重新检查,就会发现 jshint 发挥了作用。它告诉我们 app.js 文件的第 16 行 main() 后面少了一个分号 (;)

PS C:\Study\framework> grunt jshint
Running "jshint:all" (jshint) task

   app/scripts/app.js
     16 |main()
               ^ Missing semicolon.

>> 1 error in 1 file
Warning: Task "jshint:all" failed. Use --force to continue.

Aborted due to warnings.

 

4. 配合 jQuery

在使用 jQuery 脚本库的情况下,我们的函数可能是这样的,使用 jQeury 的 ready 函数来开始。

"use strict";

$( function(){
    console.info('Hello, world.');
});

 

这时使用 jshint 检查,就会发现 $ 是一个问题。

PS C:\Study\framework> grunt jshint
Running "jshint:all" (jshint) task

   app/scripts/app.js
      1 |'use strict';
         ^ Use the function form of "use strict".
      3 |$( function(){
         ^ '$' is not defined.

>> 2 errors in 1 file
Warning: Task "jshint:all" failed. Use --force to continue.

Aborted due to warnings.

第一个错误是 jshint 的规则 strict mode directive in the outermost scope of the code 导致,我们应该将 "use strict"; 放在函数内部的第一行中。

具体的原因说明:http://jslinterrors.com/use-the-function-form-of-use-strict

第二个错误是说,jshint 提示说不认识 $,'$' is not defined.

jQuery 是在另外的库中定义的,我们这里只是使用而已。可以配置 jshint 中配置 $ 是一个全局变量。

脚本修改为:

$( function(){
    "use strict";
    
    console.info('Hello, world.');
});

Gruntfile.js 修改为

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),

      // Make sure code styles are up to par and there are no obvious mistakes
    // code style check
    // 代码检查
    jshint: {
        all: [
            'app/**/*.js'
             ],
        options: {
            globals: {
                $: false,
                jQuery: false
            },
            browser: true,            // browser environment
            devel: true                // 
            }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.registerTask('default', 'Hello, world task description.', function() {
      grunt.log.writeln('Hello, world.');
  });

};

 

5. Options

任何配置选项都会被透明底传递给 JSHint, 所以,你可以配置 JSHint 支持的任何特性。支持的特性见 JSHint documentation .

这里还额外支持一些特性:

globals

Type: Object
Default: null

定义全局变量的字典,Key 就是全局变量的名字,布尔型的值用来表示可赋值。这不是 JSHint 的标准选项,但是会作为第三个参数传递给 JSHint。

jshintrc

Type: String or true
Default: null

如果设置为 true,这里的配置参数不会传递给 JSHint,JSHint 将会通过 .jshintrc 文件来获取参数。

如果设置了文件名,将会通过这个文件获取配置参数. 这个 jshintrc 文件必须是一个合法的 JSON 文件,类似这样。

{
  "curly": true,
  "eqnull": true,
  "eqeqeq": true,
  "undef": true,
  "globals": {
    "jQuery": true
  }
}

 

需要注意的是 jshintrc 文件的配置信息不会与 gruntfile.js 中的配置进行合并。

extensions

Type: String
Default: ''

需要检查的非 dot-js 扩展名列表。

ignores

Type: Array
Default: null

需要忽略的文件和目录列表. 将会覆盖 .jshintignore 文件。

force

Type: Boolean
Default: false

设置为 true 将会报告 JSHint 错误,而不会将任务失败掉。

reporter

Type: String
Default: null

Allows you to modify this plugins output. By default it will use a built-in Grunt reporter. Set the path to your own custom reporter or to one of the built-in JSHint reporters: jslint or checkstyle.

允许修改输出插件,默认使用 Grunt 内置的报告器. 可以配置为自定义的报告器路径,或者 JSHint 内置的报告器之一: jslint 或者 checkstyle。

See also: Writing your own JSHint reporter.

可以指定一个外部的报告器,例如: jshint-stylish:

首先通过 npm 进行安装。

$ npm install --save-dev jshint-stylish
然后进行配置
options: {
    reporter: require('jshint-stylish')
}

 

reporterOutput

Type: String
Default: null

配置报告的输出路径. 如果配置,输出将不会输出到标准输出流,而是这个设置的路径。

示例

Wildcards

In this example, running grunt jshint:all (or grunt jshint because jshint is a multi task) will lint the project's Gruntfile as well as all JavaScript files in the lib and test directories and their subdirectorieses, using the default JSHint options.

下面的这个例子,执行 grunt jshint:all ( 由于 jshint 是一个多任务的任务,可以直接使用 grunt jshint,  ) 将会使用默认的 JSHint 配置。检查 Gruntfile.js,lib 下面的任何 js 文件,test 下面的任何 js 文件,

// Project configuration.
grunt.initConfig({
  jshint: {
    all: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js']
  }
});

 

Linting before and after concatenating

下面的这个例子中,执行 grunt jshint 将会检查 'beforeconcat' 和 'afterconcat' 的所有文件,这并不理想,因为 dist/output.js 会在 grunt-contrib-concat plugin 的 concat 任务创建它之前被检查。

在这种情况下,应该先检查 'beforeconcat' 中的文件, 然后合并文件,最后再检查 'afterconcat' 中的文件,这样执行:grunt jshint:beforeconcat concat jshint:afterconcat.

// Project configuration.
grunt.initConfig({
  concat: {
    dist: {
      src: ['src/foo.js', 'src/bar.js'],
      dest: 'dist/output.js'
    }
  },
  jshint: {
    beforeconcat: ['src/foo.js', 'src/bar.js'],
    afterconcat: ['dist/output.js']
  }
});

 

Specifying JSHint options and globals

这个例子演示了定制 JSHint 的配置. 注意在 grunt jshint:uses_defaults 执行的时候,将会使用默认的配置, 但是当 grunt jshint:with_overrides 执行的时候,将使用合并之后的配置。

// Project configuration.
grunt.initConfig({
  jshint: {
    options: {
      curly: true,
      eqeqeq: true,
      eqnull: true,
      browser: true,
      globals: {
        jQuery: true
      },
    },
    uses_defaults: ['dir1/**/*.js', 'dir2/**/*.js'],
    with_overrides: {
      options: {
        curly: false,
        undef: true,
      },
      files: {
        src: ['dir3/**/*.js', 'dir4/**/*.js']
      },
    }
  },
});

 

Ignoring specific warnings

如果希望忽略特定的警告:

[L24:C9] W015: Expected '}' to have an indentation at 11 instead at 9.

可以通过在警告标识之前加上减号 (-) 来关掉它。

grunt.initConfig({
  jshint: {
    ignore_warning: {
      options: {
        '-W015': true,
      },
      src: ['**/*.js'],
    },
  },
});

 




posted on 2015-09-22 23:07  冠军  阅读(18286)  评论(0编辑  收藏  举报