JavaScript Code checker tool-jshint

Source: Internet
Author: User
Tags sublime text

Static code inspection is an indispensable part of development work, after all, for the programmatic work of the eyes of the person is not reliable, let alone the eyes to see their own code. Even if the final run result is passed, there may be undefined variables, defined but last unused variables, semicolons with no addition (see Team Rules), and other issues. The tools that give power are indispensable.

In this article to introduce the jshint before the JSLint, Douglas's work, should be a companion to the essence of JavaScript ... Ask you to use its rules, for a flexible language such as JavaScript, or to use a flexible tool, jshint is that.

Installation

First you need to install Nodejs and NPM, then npm install-g jshint.

This allows you to use Jshint with the command line.

Of course he also provides a huge number of editor plugins, such as Sublime Text 3.

And plugins like grunt or gulp.

Configuration

You can use it after installation.

Command line Direct: jshint myfile.js is OK, the command line can display errors or warnings.

The editor is generally displayed directly on the line number of errors or warnings. For example Sublime3, under the current file, the shortcut key ctrl+alt+j will display the message ( ctrl+alt+c off information Display):

More shortcuts to see the plugin settings, can be customized.

However, these displays are jshint default configurations, and we can customize the configuration to better meet the requirements.

It is also very simple to create a. jshintrc file under the project root, which is the Jshint configuration file, Jshint will automatically recognize the file and check your files according to the rules.

(under Windows to establish the front with the point of the file will not be built, a method directly in the sublime text, another way to add a point after the file name)

The Jshint configuration is divided into four categories:

1, enforcing: If these properties are set to True, it indicates that the code style is strict enough, such as whether to use strict (strict) mode, variable hump name, is not for-in loop must have hasownproperty and so on

2, relaxing: such as whether to use a semicolon, whether to support the next generation ES syntax and so on.

3. Environments: The environment in which your code resides (Nodejs, browser, JQuery. )

4, custom global properties, such as our nej and regular, these two global variables jshint is not known, put here Jshint will not report error message.

The default configuration of Jshint look here: Jshint default configuration (Sublime plugin custom default configuration, you can see in the configuration of the plugin, you can even modify it directly)

Explanation of these configurations: a detailed configuration

are English, but with the level of 46 level and Youdao translation, basic wood problems. The following is a simple configuration example.

{    "strict"   : false,    "Undef"    : True,         "unused"   : True,    "ASI"      : True,    "evil"     : false,    "browser": True,    "devel": True,    "Globals"  : {         "Nej": True,        "Regular": True    }        }

Sometimes, we do not want it to check some files (such as some library files), this time you can create a new . jshintignore file, write the file name that needs to be ignored (support wildcard character), also put in the project root directory.

Build/src/**/tmp.js

Custom Reporter

Jshint Source has a reporter.js, the definition of error message to change how to output, can also be customized. The default is this:

"Use strict"; module.exports = {  Reporter:function (res) {    var len = res.length;    var str = "";    Res.foreach (function (r) {      var file = r.file;      var err = R.error;      str + = file + ": Line" + Err.line + ", col" +        Err.character + "," + Err.reason + "\ n";    });    if (str) {      process.stdout.write (str + "\ n" + len + "error" +        (len = = = 1)? "": "S") + "\ n");}}  ;

The basic format is:

Module.exports = {  Reporter:function (reporter) {    //...  }};

Each reporter conforms to a certain format:

{  file:        [string, filename]  error: {    id:        [string, usually ' (Error) '],    code:      [String, Error/warning code],    Reason:    [string, error/warning message],    evidence:  [String, a piece of code that Generated this error] line    :      [number]    character: [number]    scope:     [string, message scope;                Usually ' (main) ' Unless the code is eval ' ed]    [+ A few other legacy fields so you don ' t need to worry about.]  }}

For example, you could let him print to a TXT file instead of outputting it to the console (I don't know why the asynchronous write to the file has been unsuccessful, and finally had to use the sync function):

' Use strict '; var fs = require (' FS '); module.exports = {  Reporter:function (res) {    var len = res.length;    var str = ';    var filename = ';    Res.foreach (function (r, i) {      filename = r.file;      var err = R.error;      if (i = = 0) str + = filename + ' \ n ';      str + = ' line ' + Err.line + ', col ' +        Err.character + ', ' + Err.reason + ' \ n ';    }    ; if (str) {      var output = str + ' \ n ';      Fs.writefilesync (' message.txt ', Output);}}  ;

Command line execution:

Jshint--reporter=myreporter.js Myfile.js

The same can be a step closer, if you want to check all the files that are checked, and then save the results to txt:

//Code-check.js 
var fs = require (' FS '); var path = require (' path '); var exec = require (' child_process '). Exec;var C Urpath = Path.join (PROCESS.CWD (), ' src ', ' javascript '), function Traveldir (dir, callback) {Fs.readdirsync (dir). ForEach (function (file) {var pathname = path.join (dir, file); if (Fs.statsync (pathname). Isdirectory ()) {Traveldir (pathname, callback); } else {callback (pathname); } });} Fs.writefilesync (' message.txt ', '); Traveldir (Curpath, function (file) {exec (' jshint--reporter=reporter.js ' + file); });
Reporter.js
' Use strict '; var fs = require (' FS '); module.exports = { Reporter:function (res) { var len = res.length; var str = '; var filename = '; Res.foreach (function (r, i) { filename = r.file; var err = R.error; if (i = = 0) str + = filename + ' \ n '; str + = ' line ' + Err.line + ', col ' + Err.character + ', ' + Err.reason + ' \ n '; } ; if (str) { var output = str + ' \ n '; Fs.appendfilesync (' message.txt ', Output);}} ;

As long as node Code-check is ready.

However, the sublime plugin does not know how to customize it.

Api

Jshint a number of interfaces that can be used both in the browser and in the Nodejs.

The browser first loads the Jshint.js file:

<script src= "Node_modules/jshint/dist/jshint.js" ></script>

First check if the JS statement has errors:

var result = Jshint (source, Options, Predef)

Source is the code you want to check, either a string or an array, and each item represents a line of code.

Options also mentioned above for configuration items, but not including globals

Predef was said above globals.

When result returns false, there is an error in the representation statement, and the call to Jshint.data () will get the details of the error, as shown in the following example:

var Source = [    ' function () {Console.log ("a")} ',    ' x = 3 ']var options = {    Undef:true}var predef = {    x:tr Ue}var result = Jshint (source, Options, Predef) Console.log (Jshint.data ())

The browser's console prints out the wrong details, so we can even make an error report, just like a code-checking platform inside the company.

But there's a problem, it's impossible for us to knock the code one line at a parameter, either AJAX or server-side requests, see here.

So, it's most convenient to use in the node environment:

Check.js
var jshint = require (' Jshint '). Jshint, FS = require (' FS '), files = [];p Rocess.argv.forEach (function (val) {Files.push (val)}) Console.log ('------- ----------------------------------') for (var i = 2; i < files.length; i++) {Fs.readfile (Files[i], function (err, data {if (err) {Console.log (' Error: ' + err) return} if (Jshint (data.tostring ())) {console.log (' File ' + files[i] + ' has no errors! ') } else {Console.log (' Errors in file ' + files[i]); Console.log (') var out = Jshint.data (), errors = out.errors; for (j = 0; J < Errors.length; J + +) {Console.log (errors[j].line + ': ' + errors[j].character + ') + Errors[j].reason + ' + ' + errors[j].evidence); } console.log (') Console.log (' Globals: ') for (var j = 0; J < Out.globals.length; J + +) {CONSOLE.LOG (' + out.globals[j]); }} console.log ('---------------------------------------------')})}

When using the

Node Check a.js b.js c.js

Last error in console output.

Sometimes mastering a tool can improve productivity by many times and learn to be a lazy person.

JavaScript Code checker tool-jshint

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.