How can I check JavaScript code for syntax errors ONLY from the command line?

寵の児 提交于 2019-12-03 05:26:15

问题


JavaScript programs can be checked for errors in IDEs or using online web apps but I'm looking for a way to detect syntax errors alone.

I've tried JSLint and JSHint and looked at their options but I haven't been able to find a combination that would exclude warnings and just shows the syntax errors.

How do I check JavaScript code for syntax errors only from the command line?


回答1:


I use acorn:

$ acorn --silent tests/files/js-error.js; echo $?
Unexpected token (1:14)
1

$ acorn --silent tests/files/js-ok.js; echo $?
0

Install via: npm -g install acorn.




回答2:


The solution is to enable jshint's --verbose option, which shows the error or warning code (e.g. E020 for Expected '}' to match '{' or W110 for Mixed double and single quotes), then grep for errors only:

jshint --verbose test.js | grep -E E[0-9]+.$



回答3:


JSHint does what you want. http://www.jshint.com/

You can configure which warnings or errors to show.

An example:

$ jshint myfile.js
myfile.js: line 10, col 39, Octal literals are not allowed in strict mode.

1 error



回答4:


Any JavaScript parser should do, acorn mentioned by @cweise is nice because it is fast and has a --silent switch.

You could also use esvalidate from the npm esprima package: http://ariya.ofilabs.com/2012/10/javascript-validator-with-esprima.html

$ npm install -g esprima
$ esvalidate js-file-with-errors.js 
js-file-with-errors.js:1: Invalid left-hand side in assignment



回答5:


I had the similar problem, but also needed to validate IE8 specific issues and validate js code in html, aspx, ascx and cshtml files.

I have created simple open source console tool (based on Microsoft.JScript.Compiler), maybe it can help you. JsParser.Cmd

It is very easy to use and it help me to validate js code in nunit tests.




回答6:


Here is an answer for a Continuous Integration scenario.

1- Checks all the JavaScript files with exclude folder, subfolder and file features.

2- Exit if there is an error.

esvalidate --version || npm install -g esprima;
find ./ -not \( -path ./exclude_folder_1 -prune \) -not \( -path ./exclude/sub_folder -prune \) -not \( -path ./exclude/sub_folder_2 -prune \) ! -name exclude_specified_file.js  -name \*.js -exec esvalidate '{}' \; | grep -v "No syntax errors detected" && echo "Javascript Syntax error(s) detected" && exit 1;


来源:https://stackoverflow.com/questions/21856097/how-can-i-check-javascript-code-for-syntax-errors-only-from-the-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!