Detecting typos in JavaScript code - javascript

In Python world, one of the most widely-used static code analysis tools, pylint has a special check, that detects typos in comments and docstrings.
Is there a way to detect typos in JavaScript code using static code analysis?
To make the question more specific, here is an example code I want to cause a warning:
// enter credntials and log in
scope.loginPage.logIn(browser.params.regularUser.login, browser.params.regularUser.password);
Here credntials is misspelled.

There is a eslint plugin built specifically for the task - eslint-plugin-spellcheck:
eslint plugin to spell check words on identifiers, Strings and comments of javascript files.
It is based on the hunspell-spellchecker library that knows how to parse and use Hunspell dictionaries of known words:
Hunspell is a spell checker and morphological analyzer designed for
languages with rich morphology and complex word compounding and
character encoding, originally designed for the Hungarian language.
Here is what it outputs for the example code provided in the question:
$ node_modules/eslint/bin/eslint.js -c eslint.json showCase.spec.js
25:8 warning You have a misspelled word: credntials on Comment spellcheck/spell-checker
The plugin is easily customizable and can check in comments, identifiers and strings.

You can use cspell. It's a very handy command line tool and finds spelling mistakes in JavaScript, TypeScript, Python, PHP, C#, C++, LaTex, Go, HTML and CSS sources.
Output for your example:
cspell ./src/code.js
code.js:1:10 - Unknown word (credntials)
./src/code.js
// enter credntials and log in
scope.loginPage.logIn(browser.params.regularUser.login, browser.params.regularUser.password);

Related

Node JS Minification

Minification process on JavaScript as per definition basically just removes blank spaces , comments . Building on this , why in Nodejs is language specification pertaining to whether code is written in ECMA5 or ECMA6 necessary ? Why not just run the minifier and minify the code by removing blank spaces and comments. Why do I need to bother whether my code is written ECMA5 OR 6 ?
Thanks in advance.
Minification process on JavaScript as per definition basically just removes blank spaces, comments.
I have no idea whose "definition" you are quoting. Minification is much, much more than squeezing out white space. Minifiers parse the entire source in order to do advanced minification. Obviously, to do that, they have to know the syntax they are parsing. If they don't know ES6 syntax, they cannot parse ES6 input. To minify ES6, you'll have to choose a minifier that supports ES6.

How to setup Eclipse to be warned about trailing comma in JavaScript

As many of us know, IE7 is not quite friendly with JavaScript code containing trailing commas, which can be a large problem for projects using modern JS framerworks and containing a lot of JS code.
In a pretty good article on the subject, the author mentions:
On the tools front, my preference for combating these devils is the Eclipse JavaScript Development Tools. The JavaScript source editor in JSDT flags trailing commas as errors: http://www.enterprisedojo.com/wp-content/uploads/2010/12/jsdtRules.png
However, using Eclipse Indigo with WTP/JSDT, I'm not seeing trailing commas as errors, and I can't find a proper setting to fix this.
How do I setup Eclipse to flag trailing commas in JavaScript as errors?
It looks like the fix for another bug involving erroneous syntax errors on the comma operator also removed the syntax error on trailing commas in initializers. That's technically correct; the standard says they're allowed and IE7 is just nonconformant. There's a feature request open asking that they be reinstated.
Slightly off topic, but you should also look into using JSLint to check the syntax of the JavaScript code. It will warn you about the trailing comma, but also about many other potential problems. There is a good plugin for Eclipse, http://marketplace.eclipse.org/content/phonegap-android-jslintjshint. The instructions for setting it up: http://www.mobiledevelopersolutions.com/home/announce-1/mds12released-nowwithjslintjshint
Make sure you're in the correct perspective (ie JavaScript as opposed to Java).
Also, I found in Helios that if I added a JS file to the project by right-clicking and adding a new 'File' (which I would then name with a .js extension) didn't make the UI pick up that it should be treated as a JS file--no syntax highlighting, checking, etc. If I added it specifically using the new JavaScript file option, it worked fine.

Fulltext search ignoring comments

I want fulltext search for my JavaScript code, but I'm usually not interested in matches from the comments.
How can I have fulltext search ignoring any commented match? Such a feature would increase my productivity as a programmer.
Also, how can I do the opposite: search within the comments only?
(I'm currently using Text Mate, but happy to change.)
See our Source Code Search Engine (SCSE). This tool indexes your code base using the langauge structure to guide the indexing; it can do so for many languages including JavaScript. Search queries are then stated in terms of abstract language tokens, e.g., to find identifiers involving the string "tax" multiplied by some constant, you'd write:
I=*tax* '*' N
This will search all indexed languages only for identifiers (in each language) following by a '*' token, followed by some kind of number. Because the tool understands language structure, it isn't confused by whitespace, formatting or interverning comments. Because it understands comments, you can search inside just comments (say, for authors):
C=*Author*
Given a query, the SCSE finds all the hits across the code base (possibly millions of lines), and offers these as set of choices; clicking on choice pulls up the file with the hit in the middle outlined where the match occurs.
If you insist on searching just raw text, the SCSE provides grep-style searches. If you have only a small set of files, this is still pretty fast. If you have a big set of files, this is a lot slower than language-structure based searches. In both cases, grep like searches get you more hits, usually at the cost of false positives (e.g., finding "tax" in a comment, or finding a variable named "Authorization_code"). But at least you have the choice.
While this doesn't operate from inside an editor, you can launch your editor (for most editors) on a file once you've found the hit you want.
Use ultraedit , It fully supports full text search ignoring comment or also within the comment search
How about NetBeans way (Find Symbol in the Navigate Menu),
It searches all variables,functions,objects etc.
Or you could customize JSLint and customize it if you want to integrate it in a web application or something like that.
I personnaly use Notepad++ wich is a great free code editor. It seems you need an editor supporting regular expression search (in one or many files). If you know Reg you can use powerfull search like in/out javascript comments...the work will be to build the right expression and test it with one file with all differents cases to be sure it will not miss things during real search, or maybe you can google for 'javascript comments regular expression' or something like...
Then must have a look at Notepad++ plugins, one is 'RegEx Helper' wich helps for building regular expressions.

How to setup Xcode for proper javascript formatting?

Xcode3 (and newer ;) doesn't properly format Javascript when I type something like:
doSomething(somewhere, function(err, result) {
It inserts a huge indentation. I tried to change Xcode formatting rules but no luck. One way or another it breaks indentations.
Is there a proper way to use Xcode for javascript development?
What worked fairly well for me is to switch the .js files to use C syntax coloring.
In XCode 4: Editor -> Syntax Coloring -> C
It still highlights numbers and strings and comments, and it indents braces in a sane way.
With some tweaking it is possible to modify the way Xcode indents JavaScript by supplying a custom xclangspec file. Xcode for formatting and syntax uses language definitions in xclangspec files kept in directory SharedFrameworks/DVTFoundation.framework/Versions/A/Resources. Since the formatting for C language works actually better for JavaScript than the Xcode original JavaScript formatting, it is possible to use some parts of definition for C in JS definition. More details you can find at http://www.conhar.com/xcode-and-javascript/.
A quick solution is to choose View -> Syntax Coloring -> Simple Coloring.
If you are okay to edit Javascript without fancy syntax highlight, this is pretty useful.
This way only the numbers and strings are colored, and the indentation stops being so annoying.
Unfortunatelly XCode has very limited formatting options.
But you can use uncrustify which is pretty good. You can find some information here:
Xcode source automatic formatting
Objective-C Tidy
These articles all talk about formatting objective-c code, however uncrustify can format the source code of various languages ;)
Hope this helps.
Uncrustify requires a .cfg file to setup which can be somewhat overwhelming. There's an alternative here

What is a good stand-alone JavaScript formatter for fixing missing semicolons?

I'm trying to retrofit/fix lots of legacy web code and unfortunately most of it is poorly formatted JavaScript. I'm looking for a batch/scriptable utility that can fix JavaScript that is missing simicolons at the end of executable statements.
I've tried the beautify-cl.js script with Rhino but that does not does not add semicolons. In addition, I have tried JSTidy thinking I could modify it to be scriptable, but it strips all comments. Considering we have something like 2000-3000 files, any solution has to be scriptable.
The following topics were referenced, however none of the solutions were sufficient for various reasons:
Javascript Beautifier - Doesn't handle semicolon
Best source code formatter for Javascript? - Not scriptable
Any ideas/solutions? Thanks in advance.
I've found a winning combination in js-beautify and Google's Closure Linter:
# legacy.js is your poorly formatted JavaScript file, and will be modified in-place
js-beautify -s 2 -n -b end-expand -x -r legacy.js && fixjsstyle legacy.js
Explanation of js-beautify options:
-s 2: indent with two spaces
-n: ensure newline at end of file
-b end-expand: puts { braces at the end of the line, but always gives } braces their own line.
-x: unescape \xNN-escaped characters in strings
-r: make changes in-place
fixjsstyle, which is installed with the Closure Linter suite, makes changes in-place by default.
This pipeline retains comments (!), indents everything (mostly) how I like, adds semicolons where appropriate, and even changes double quotes to single quotes where feasible. Both commands can be given a list of files (e.g., **/*.js), instead of just one.
To install the required packages on Mac OS X:
npm install -g js-beautify
brew install closure-linter
Obviously you'll need to do this if you want to minify the files on deployment. Missing semicolons are probably the #1 reason JS files don't minify properly, so I understand your motivation.
Write a little Python (or whatever) script to run the file through jslint, then use the output from jslint to see which lines need semicolons, then spin through the js source and add them.
I think you can be fairly fearless here, because JavaScript implicitly adds the semicolons anyway.
Update: This set of tools may be what you are looking for. The "format" tab offers missing semicolon insertion.
If you use JavaScript Utlity V2 at http://jsutility.pjoneil.net and use the formatting function, it will automatically replace missing semicolons.
In addition, if you use the compaction function, it will also replace missing semicolons so that the compaction will not cause any errors.
You shouldn't be worried about doing a mass update on a lot of legacy code for the sole purpose of inserting semi colons. That's a classic case of "doing it wrong".
How would you test the results?
How would you ensure no "functionality" (as a side effect of a bug caused by a semi colon being missing) isn't lost?
What do you think adding semi colons to all these files will get you? Beside larger files (I'm not knocking the use of semicolons) and massive amounts of untested code changes?
As gumbo said, use jslint. I would use it on the files as you edit them in your day to day work. As you edit these files, presumably you will be testing changes to the file at that time. That would be the most ideal time to go crazy with semi colon insertion.
Also, if you're concerned about keeping 2000-3000 legacy javascript files alive and supported, you've got far bigger problems than semi colons
If http://jsutility.pjoneil.net is throwing too much errors (and be unable to format it), you may try to compress it with: http://refresh-sf.com/yui/ (which will add missing semicolons) and then go back to pjoneil.net formatter to obtain the pretty code with semicolons.
If you are using Visual Studio Code then Prettier Formatter is the way to go:
https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode
You simply install it and then on the keyboard shortcut to Format Document, the js file is reformatted but also any missing semicolons are automatically filled.
Enjoy!

Categories

Resources