代码检查工具jshint和csslint

时间:2022-08-01 17:38:26

前面的话

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

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

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

安装

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

  一般地,使用npm来安装jshint。所以,首先需要安装nodejs,然后使用npm install jshint -g命令来安装jshint

代码检查工具jshint和csslint

  然后就可以通过命令'jshint xx.js'来检测代码

代码检查工具jshint和csslint

【sublime插件】

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

代码检查工具jshint和csslint

  安装完成后,一般需要将'node_path'设置为正确的路径

代码检查工具jshint和csslint

  然后在当前文件下,使用快捷键Ctrl+Alt+J 就会显示信息

代码检查工具jshint和csslint

配置

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

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

代码检查工具jshint和csslint

  JSHint的配置分为四类:

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

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

  3、Environments(环境):如果这些属性设置为true,表示代码所处的环境

  4、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安装即可

代码检查工具jshint和csslint

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

代码检查工具jshint和csslint

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

【规则】

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

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

  1、潜在错误

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

  2、兼容性

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 需要使用备用字体

  3、性能

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

  4、可维护性

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

  5、可访问性

outline-none    禁用outline:none

  6、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
}

相关文章