问题
Is it possible to run JSLint
on one or more .js files by having JSLint loaded afterwards in the header from debugging/developer console in chrome or firefox?
The reason that I want to do that is that I want to print in console.log()
the parsing of JSLint
in JSON
,it says in documentation:
// You can obtain the parse tree that JSLint constructed while parsing. The
// latest tree is kept in JSLINT.tree. A nice stringication can be produced
// with
// JSON.stringify(JSLINT.tree, [
// 'string', 'arity', 'name', 'first',
// 'second', 'third', 'block', 'else'
// ], 4));
回答1:
You can run JSLint on JavaScript code using the below syntax:
var code = "var a = 1 + 2;";
JSLINT(code);
And you can print the syntax tree as you have mentioned in the question.
Now in your case, you need to read the JavaScript source from JavaScript files. You can make an AJAX call to read the source code of the JavaScript file into a variable. Then make a call to JSLINT as above passing that variable. A sample using jQuery would be like below.
$(function() {
// Include jslint.js
$('<script src="http://localhost/yourapp/jslint.js">').appendTo("head");
// Read JavaScript file contents into 'code'
$.get('http://localhost/yourapp/somescript.js', function(code) {
// Run JSLINT over code
JSLINT(code);
// Print the parse tree
console.log(JSON.stringify(JSLINT.tree, [
'string', 'arity', 'name', 'first',
'second', 'third', 'block', 'else'
], 4));
});
});
Depending on what you are trying to achieve, a standalone JavaScript console (eg. NodeJS) would be a better alternative than a browser console. I guess there exist Node packages for JSLint. But if you want to include it manually you can simply do it as below.
First add the below line at the end of jslint.js
exports.JSLINT = JSLINT;
Then write your code in say mycode.js.
var fs = require("fs");
var jslint = require("./jslint.js");
fs.readFile("./test.js", function(err, code) {
var source = code.toString('ascii');
jslint.JSLINT(source);
console.log(JSON.stringify(jslint.JSLINT.tree, [
'string', 'arity', 'name', 'first',
'second', 'third', 'block', 'else'
], 4));
},"text");
Then run your code from console as:
node mycode.js
来源:https://stackoverflow.com/questions/11884224/run-jslint-on-a-js-file-from-debugging-console-in-chrome-or-firefox