1. 程式人生 > >代碼檢查工具jshint和csslint

代碼檢查工具jshint和csslint

sub ever 發生器 conf win 多行 oval rul 定義

前面的話

  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 xx.js‘來檢測代碼

技術分享

【sublime插件】

  在sublime編輯器中也可以使用jshint插件。使用快捷鍵 Ctrl+Shift+P 呼出Sublime命令面板;然後鍵入install,並選擇Package Control:Install Package;然後再鍵入jshint,並選擇JSHint Gutter

技術分享

  安裝完成後,一般需要將‘node_path‘設置為正確的路徑

技術分享

  然後在當前文件下,使用快捷鍵Ctrl+Alt+J 就會顯示信息

技術分享

配置

  在項目根目錄下建立一個 .jshintrc 文件,這個文件就是JSHint的配置文件,JSHint會自動識別這個文件,根據這裏面的規則對文件進行檢查

  [註意]windows下並不允許新建文件名前面帶點的文件,解決辦法一種是直接在Sublime Text裏建立;另一種是使用命令行touch命令建立

技術分享

  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安裝即可

技術分享

  安裝sublime插件的方式也類似於jshint

技術分享

  在項目根目錄下建立一個 .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                    [email protected]
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
}

代碼檢查工具jshint和csslint