代码检查工具jshint和csslint

前面的话

  Douglas Crockford大神根据本身的理念用JavaScript写了一个JavaScript代码规范检查工具,这就是JSLint。后来很是流行,也的确帮助了广大的JavaScript程序员。可是,大神对于本身的代码规范不作丝毫的妥协,对开源社区的反馈的回应也不礼貌。因而,JSLint从一个帮助程序员规范代码,避免Bug的工具,变成了一个让代码像Crockford的工具。在最不信神的IT界,这固然不能忍了css

  2011年,一个叫Anton Kovalyov的前端程序员借助开源社区的力量弄出来了JSHint,该工具的思想基本上和JSLint是一致的,但具备如下几点优点:一、可配置规则。二、社区支持度高。三、可定制结果报表html

  相对应地,CSS的代码检查工具是csslint。本文将详细介绍jshint和csslint前端

 

安装

  JSHint的官方地址是http://jshint.com/,GitHub 地址:https://github.com/jshint/jshintnode

  通常地,使用npm来安装jshint。因此,首先须要安装nodejs,而后使用npm install jshint -g命令来安装jshintjquery

  而后就能够经过命令'jshint xx.js'来检测代码git

【sublime插件】程序员

  在sublime编辑器中也可使用jshint插件。使用快捷键 Ctrl+Shift+P 呼出Sublime命令面板;而后键入install,并选择Package Control:Install Package;而后再键入jshint,并选择JSHint Guttergithub

  安装完成后,通常须要将'node_path'设置为正确的路径web

  而后在当前文件下,使用快捷键Ctrl+Alt+J 就会显示信息正则表达式

 

配置

  在项目根目录下创建一个 .jshintrc 文件,这个文件就是JSHint的配置文件,JSHint会自动识别这个文件,根据这里面的规则对文件进行检查

  [注意]windows下并不容许新建文件名前面带点的文件,解决办法一种是直接在Sublime Text里创建;另外一种是使用命令行touch命令创建

  JSHint的配置分为四类:

  一、Enforcing(加强):若是这些属性设置为true,JSHint会对代码进行更严格的检查,好比是否使用严格(strict)模式、变量驼峰式命名、是否是for-in循环里必须得有hasOwnProperty等等

  二、Relaxing(松弛):若是这些属性设置为true,JSHint会容忍规则中定义的状况出现。好比是否使用分号,是否支持下一代ES语法等等。

  三、Environments(环境):若是这些属性设置为true,表示代码所处的环境

  四、globals(全局变量):自定义的一些全局变量

【加强】

复制代码
bitwise               禁用位运算符
camelcase             使用驼峰命名(camelCase)或全大写下划线命名(UPPER_CASE)
curly                 在条件或循环语句中使用{}来明确代码块
eqeqeq                使用===和!==替代==和!=
es3                   强制使用ECMAScript 3规范
es5                   强制使用ECMAScript 5规范
forin                 在for in循环中使用Object.prototype.hasOwnProperty()来过滤原型链中的属性
freeze                禁止复写原生对象(如Array, Date)的原型
immed                 匿名函数调用必须(function() {}());而不是(function() {})();
indent                代码缩进宽度
latedef               变量定义前禁止使用
newcap                构造函数名首字母必须大写
noarg                 禁止使用arguments.caller和arguments.callee
noempty               禁止出现空的代码块
nonew                 禁止使用构造器
plusplus              禁止使用++和–-
quotemark             统一使用单引号或双引号
undef                 禁止使用不在全局变量列表中的未定义的变量
unused                禁止定义变量却不使用
strict                强制使用ES5的严格模式
trailing              禁止行尾空格
maxparams             函数能够接受的最大参数数量
maxdepth              代码块中能够嵌入{}的最大深度
maxstatement          函数中最大语句数
maxcomplexity         函数的最大圈复杂度
maxlen                一行中最大字符数
复制代码

【松弛】

复制代码
asi               容许省略分号
boss              容许在if,for,while语句中使用赋值
debug             容许debugger语句
eqnull            容许==null
esnext             容许使用ECMAScript 6
evil                容许使用eval
expr                  容许应该出现赋值或函数调用的地方使用表达式
funcscope             容许在控制体内定义变量而在外部使用
globalstrict          容许全局严格模式
iterator             容许__iterator__
lastsemic             容许单行控制块省略分号
laxbreak              容许不安全的行中断
laxcomma            容许逗号开头的编码样式
loopfunc              容许循环中定义函数
maxerr             JSHint中断扫描前容许的最大错误数
multistr            容许多行字符串
notypeof            容许非法的typeof操做
proto                 容许 proto
smarttabs            容许混合tab和space排版
shadow               容许变量shadow
sub                 容许使用person[‘name’]
supernew            容许使用new function() {…}和new Object
validthis            容许严格模式下在非构造函数中使用this
noyield             容许发生器中没有yield语句
复制代码

【环境】

复制代码
browser              Web Browser (window, document, etc)
browserify           Browserify (node.js code in the browser)
jquery               jQuery
node                 Node.js
qunit                QUnit
typed                Globals for typed array constructions
worker               Web Workers
wsh                  Windows Scripting Host
复制代码

【全局变量】

globals: {
      jQuery: true,
      console: true,
      module: true
    }

  JSHint的默认配置以下所示

复制代码
{
    // JSHint Default Configuration File (as on JSHint website)
    // See http://jshint.com/docs/ for more details

    "maxerr"        : 50,       // {int} Maximum error before stopping

    // Enforcing
    "bitwise"       : true,     //Prohibit bitwise operators (&, |, ^, etc.)
    "camelcase"     : false,    //Identifiers must be in camelCase
    "curly"         : true,     //Require {} for every new block or scope
    "eqeqeq"        : true,     //Require triple equals (===) for comparison
    "forin"         : true,     //Require filtering for in loops with obj.hasOwnProperty()
    "freeze"        : true,     //prohibits overwriting prototypes of native objects
    "immed"         : false,    //Require immediate invocations to be wrapped in parens
    "latedef"       : false,    //Require variables/functions to be defined before being used
    "newcap"        : false,    //Require capitalization of all constructor functions
    "noarg"         : true,     //Prohibit use of `arguments.caller` and `arguments.callee`
    "noempty"       : true,     //Prohibit use of empty blocks
    "nonbsp"        : true,     //Prohibit "non-breaking whitespace" characters.
    "nonew"         : false,    //Prohibit use of constructors for side-effects
    "plusplus"      : false,    //Prohibit use of `++` and `--`
    "quotmark"      : false,   
    "undef"         : true,     //Require all non-global variables to be declared
    "unused"        : true,     
    "strict"        : true,     //Requires all functions run in ES5 Strict Mode
    "maxparams"     : false,    // {int} Max number of formal params allowed per function
    "maxdepth"      : false,    // {int} Max depth of nested blocks (within functions)
    "maxstatements" : false,    // {int} Max number statements per function
    "maxcomplexity" : false,    // {int} Max cyclomatic complexity per function
    "maxlen"        : false,    // {int} Max number of characters per line
    "varstmt"       : false,    

    // Relaxing
    "asi"           : false,     //Tolerate Automatic Semicolon Insertion (no semicolons)
    "boss"          : false,     //Tolerate assignments where comparisons would be expected
    "debug"         : false,     //Allow debugger statements e.g. browser breakpoints.
    "eqnull"        : false,     //Tolerate use of `== null`
    "esversion"     : 5,         
    "moz"           : false,     //Allow Mozilla specific syntax                                 
    "evil"          : false,     //Tolerate use of `eval` and `new Function()`
    "expr"          : false,     //Tolerate `ExpressionStatement` as Programs
    "funcscope"     : false,     //Tolerate defining variables inside control statements
    "globalstrict"  : false,     //Allow global "use strict" (also enables 'strict')
    "iterator"      : false,     //Tolerate using the `__iterator__` property
    "lastsemic"     : false,     
    "laxbreak"      : false,     //Tolerate possibly unsafe line breakings
    "laxcomma"      : false,     //Tolerate comma-first style coding
    "loopfunc"      : false,     //Tolerate functions being defined in loops
    "multistr"      : false,     //Tolerate multi-line strings
    "noyield"       : false,     //Tolerate generator functions with no yield statement
    "notypeof"      : false,     //Tolerate invalid typeof operator values
    "proto"         : false,     //Tolerate using the `__proto__` property
    "scripturl"     : false,     //Tolerate script-targeted URLs
    "shadow"        : false,     //Allows re-define variables later in code 
    "sub"           : false,     
    "supernew"      : false,     //Tolerate `new function () { ... };` and `new Object;`
    "validthis"     : false,     //Tolerate using this in a non-constructor function

    // Environments
    "browser"       : true,     // Web Browser (window, document, etc)
    "browserify"    : false,    // Browserify (node.js code in the browser)
    "couch"         : false,    // CouchDB
    "devel"         : true,     // Development/debugging (alert, confirm, etc)
    "dojo"          : false,    // Dojo Toolkit
    "jasmine"       : false,    // Jasmine
    "jquery"        : false,    // jQuery
    "mocha"         : true,     // Mocha
    "mootools"      : false,    // MooTools
    "node"          : false,    // Node.js
    "nonstandard"   : false,    // Widely adopted globals (escape, unescape, etc)
    "phantom"       : false,    // PhantomJS
    "prototypejs"   : false,    // Prototype and Scriptaculous
    "qunit"         : false,    // QUnit
    "rhino"         : false,    // Rhino
    "shelljs"       : false,    // ShellJS
    "typed"         : false,    // Globals for typed array constructions
    "worker"        : false,    // Web Workers
    "wsh"           : false,    // Windows Scripting Host
    "yui"           : false,    // Yahoo User Interface

    // Custom Globals
    "globals"       : {}        // additional predefined global variables
}
复制代码

  有时候,咱们不但愿它检查一些文件(好比一些库文件),这时候能够新建一个 .jshintignore 文件,把须要忽略的文件名写在里面(支持通配符),一样放到项目根目录下便可

build/
src/**/tmp.js

 

CSSLint

  CSSLint的安装比较简单,使用npm install csslint -g安装便可

  安装sublime插件的方式也相似于jshint

  在项目根目录下创建一个 .csslintrc 文件,这个文件就是CSSLint的配置文件,CSSLint会自动识别这个文件,根据这里面的规则对文件进行检查 

【规则】

  就CSSLint而言,最重要的规则是确保CSS中不存在解析错误。解析错误一般意味着错误地输入字符,并致使代码变为无效的CSS。这些错误可能致使浏览器删除属性或整个规则

  CSSLint的规则主要包括如下6种

  一、潜在错误

box-model              设置width或height的同时,还设置为border或padding,则必须设置box-sizing
display-property-grouping 设置display属性时,不能包含其余没必要要的代码,如display:inline,又设置height值
duplicate-properties      不容许包含重复的样式属性
empty-rules              不容许包含空样式规则
known-properties         不容许使用不识别的样式属性

  二、兼容性

复制代码
adjoining-classes           不要使用相邻选择器,如.a.b{}
box-sizing                 box-sizing不要与相关属性同用
compatible-vendor-prefixes     须要兼容第三方前缀
gradients                 须要全部的渐变定义
text-indent              不能使用负值
vendor-prefix             第三方前缀和标准属性一块儿使用
fallback-colors            须要指定备用颜色
star-property-hack          不能使用'*'hack
underscore-property-hack       不能使用'_'hack
bulletproof-font-face          须要使用备用字体
复制代码

  三、性能

复制代码
font-faces                 不能使用超过5个web字体
import                    禁止使用@import
regex-selectors              禁止使用属性选择器中的正则表达式选择器
universal-selector           禁止使用通用选择器*
unqualified-attributes       禁止使用不规范的属性选择器
zero-units                  0后面不要加单位
overqualified-elements       使用相邻选择器时,不要使用没必要要的选择器
shorthand                 简写样式属性
duplicate-background-images    相同的url在样式表中不超过一次
复制代码

  四、可维护性

floats       不使用超过10次的浮动
font-sizes    不使用超过10次的font-size
ids          不使用id选择器
important     不使用!important

  五、可访问性

outline-none    禁用outline:none

  六、OOCSS

qualified-headings    <h1-h6>应该被设置为顶级样式,因此.box h3{}会提示警告;而h3{}则不会
unique-headings    当多个规则定义针对同一标题的属性时,会出现警告

   CSSLint的经常使用配置以下

复制代码
{
    "adjoining-classes":false,
    "box-sizing":false,
    "box-model":false,
    "compatible-vendor-prefixes": false,
    "floats":false,
    "font-sizes":false,
    "grandients":false,
    "important":false,
    "known-properties":false,
    "outline-none":false,
    "qualified-headings":false,
    "regex-selectors":false,
    "shorthand":false,
    "text-indent":false,
    "unique-headings":false,
    "universal-selector":false,
    "unqualified-attributes":false
}
复制代码
相关文章
相关标签/搜索