Disabling all jslint rules with Inline Comments - javascript

/* eslint-disable */ is the inline comment that disables/ignores all the eslint rules in a js file. Similarly is there any way to disable all jslint rules with inline comment within a js file?

TL;DR -- No.
You used to be able to have JSLint ignore sections of code, but that was removed no later than April of 2013.
Here are some options:
Roll your own ignore
In another answer, I've shown how to hack JSLint yourself if you really really to recreate this functionality. You'd probably have to change some line numbers, but you get the idea.
Id any code smell
The real question, however, is what specifically is it that you want JSLint to ignore? Often there's a code smell associated with wanting to skip something that you might, on further consideration, prefer to fix another way. Or if there's a specific JSLint option that matches what you want to skip, you could turn that option on.
"Quarantine" your code
As an alternative to turning JSLint off for a few lines if you know you want to keep the code, I often put utility functions that, for whatever reason, aren't JSLint happy, in a separate file so that I can have clean files elsewhere in my codebase.

Related

Avoid reporting warnings/errors for rule change until file is edited for another reason?

I've just made a load of updates to a project and changed the TypeScript, ESLint rules etc. One thing I did was introduce the no semi-colon rule.
Now there are warnings/errors about every single semi colon still in the project (obviously this is what I wanted). There are also errors related to the TypeScript config changes I made. But I don't want to fix them all in 1 PR as that will be massive.
Is it possible to ignore these issues unless you open / edit the file somehow or what is the best way to achieve this?

Rule is disabled but not violated

The Story:
We are using ESLint with a set of different plugins. Long ago, in a specific JS-file (page object for Protractor) one of the rules was disabled via a comment at the top of the script:
/* eslint-disable protractor/no-by-xpath */
because there was an xpath() method used that violated the no-by-xpath and at that time we have not found a way to workaround it and we simply disabled the check.
The Problem:
Nowadays, the page object source code changed and there is no xpath() method used anymore. But, the rule is left disabled since the comment disabling it is still there.
The Question:
Our goal is to find the places in the source code where rules are disabled, but not violated. Does ESLint provide anything to report that? How would you approach the problem?
Would appreciate any insights and hints.
No, ESLint doesn't provide anything for this. This feature has been requested a few times, but was deemed unfit for ESLint core. Suggested way of doing something like that would be to create another tool that uses ESLint's Node API, and does two runs on all of the files, once with --no-inline-config flag on, and once with that flag off, then compare results and if files with inline eslint configs don't have any differences, then comments can be removed.

Catch JavaScript errors from compressed files

I catch JS errors by subscribing to window.onerror event, so if someone catches 'undefined variable' error, I send it to server for debugging purposes.
As you know this event return 'message of error', 'url' and 'line' where error occurred.
The problem are in compressed files.
If file is compressed, all the code goes in one line and it's big problem to determine the exact place of error.
Is there any solution for this problem?
JavaScript compressors usually do two things:
Remove all unneccessary white-space (“unneccessary” in terms of syntactical validaty).
shorten variable names, if possible. This applies to local variables, i.e. those which are not in the global scope or members of an object.
There are some other optimizations, such as function inlining, but these are usually not so problematic.
As for the first point, you can run the code through one of the many JavaScript source formatters. This should give you a pretty readable JavaScript file.
As for the second point, the obfuscation is usually not reversible. If “speaking” variable names like width, height or whatever have been changed to a or b, you cannot know what they were meant to express in the first place.
If this problem applies to an open source product, you can usually download the sources and try to reconstruct the problem with them.
If it's closed source, and only “beautifying” the code doesn't help, you have to write a bug report to the vendor.
No. There is no way to "unminify" a JavaScript include for the purposes of error logging.
Your best bet is probably to log the Error Type in the hope that this will help you debug the problem.
If you really want to get to the specific line number you would have to remove the minimization and rely on browser caching to attain performance.
I think you could use source maps...
Its a file that can be generated when minifying, and can be used to map the line/character of the minified file to the original source.
http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/
The best answer regarding this question I found here
Malyw suggests yo use Uglify with max-line-len option and sourcemaps.
That's probably the best solution to identify exact place in code

How to make JSHint warn when HTML tags are included in JavaScript code?

In our dev shop, we use client-side templates and include no HTML tags in our JavaScript code.
In our continuous integration process, we run JSHint automatically after every commit (post-build action in Jenkins) to verify compliance with our coding style guidelines.
I'd like to configure JSHint so it throws a warning when it finds an HTML tag in a .js file.
How can I accomplish this? I've searched, but I can find no examples of HTML tag warnings nor custom rules for JSHint.
Edit:
Just to be clear, I'm trying to catch code like this:
var newDiv = "<div>Hello World!</div>";
$("body").append(newDiv);
If I could get JSHint to produce a warning for the first line in the example above, that'd be fantastic.
Second Edit:
If there's post-build plugin for Jenkins that could throw a validation error if HTML is found in a .js file, then that'd also be a great alternative solution.
The Answer
No, jSHint does not support disallowing arbitrary string contents or HTML tags inside of strings. It also does not support custom rules, for now, though the author has discussed adding a public api in the future.
My speculation (as I am not an insider) on WHY
The solution you're proposing (disallowing any HTML tags in any scenario) would disallow a wide variety of highly valid use cases, regardless of how you feel about creating HTML in js. I understand that it is what your team wants to do, but such a blunt force rule is not going to have the general applicability of the rest of jsHints rules. Their focus is on enforcing style rules. Since you're disallowing all HTML tags in strings this is really more of a content validation than a style one. It would eliminate the following content examples, which are irrelevant to DOM injection/separation of concerns.
For instance:
var example="I'm writing a report on <div> tags and css";
or
var htmlStrippedText = text.replace("<div>","");
My Advice
Of course lack of broad applicability is not a reason for YOU not to do this. If you really want to filter content like this, use a command line script to search with a regex. Since you only want to see if there is HTML, not whether its valid, you can just search for stuff in the form <[div|span|body|html... as well as document.createElementand it should be fine (although you might have to be more creative if you want to allow it inside of comments). Just don't use nodejs to run your script with JS or it will fail to validate itself. :)
Of course none of this will stop a determined developer:
var topSecretDOMObject,topSecretFunction,topSecretArgument;
topSecretFunction = "create"+"Element";
topSecretArgument = "d" + "i" + "v";
topSecretDOMObject = document[topSecretFunction](topSecretArgument);

What are the arguments against the inclusion of server side scripting in JavaScript code blocks?

I've been arguing for some time against embedding server-side tags in JavaScript code, but was put on the spot today by a developer who seemed unconvinced
The code in question was a legacy ASP application, although this is largely unimportant as it could equally apply to ASP.NET or PHP (for example).
The example in question revolved around the use of a constant that they had defined in ServerSide code.
'VB
Const MY_CONST: MY_CONST = 1
If sMyVbVar = MY_CONST Then
'Do Something
End If
//JavaScript
if (sMyJsVar === "<%= MY_CONST%>"){
//DoSomething
}
My standard arguments against this are:
Script injection: The server-side tag could include code that can break the JavaScript code
Unit testing. Harder to isolate units of code for testing
Code Separation : We should keep web page technologies apart as much as possible.
The reason for doing this was so that the developer did not have to define the constant in two places. They reasoned that as it was a value that they controlled, that it wasn't subject to script injection. This reduced my justification for (1) to "We're trying to keep the standards simple, and defining exception cases would confuse people"
The unit testing and code separation arguments did not hold water either, as the page itself was a horrible amalgam of HTML, JavaScript, ASP.NET, CSS, XML....you name it, it was there. No code that was every going to be included in this page could possibly be unit tested.
So I found myself feeling like a bit of a pedant insisting that the code was changed, given the circumstances.
Are there any further arguments that might support my reasoning, or am I, in fact being a bit pedantic in this insistence?
Script injection: The server-side tag could include code that can break the JavaScript code
So write the code properly and make sure that values are correctly escaped when introduced into the JavaScript context. If your framework doesn't include a JavaScript "quoter" tool (hint: the JSON support is probably all you need), write one.
Unit testing. Harder to isolate units of code for testing
This is a good point, but if it's necessary for the server to drop things into the page for code to use, then it's necessary. I mean, there are times when this simply has to be done. A good way to do it is for the page to contain some sort of minimal block of data. Thus the server-munged JavaScript on the page really isn't "code" to be tested, it's just data. The real client code included from .js files can find the data and use it.
Thus, the page may contain:
<script>
(function(window) {
window['pageData'] = {
companyName: '<%= company.name %>',
// etc
};
})(this);
</script>
Now your nicely-encapsulated pure JavaScript code in ".js" files just has to check for window.pageData, and it's good to go.
Code Separation : We should keep web page technologies apart as much as possible.
Agreed, but it's simply a fact that sometimes server-side data needs to drive client-side behavior. To create hidden DOM nodes solely for the purpose of storing data and satisfying your rules is itself a pretty ugly practice.
Coding rules and aesthetics are Good Things. However, one should be pragmatic and take everything in perspective. It's important to remember that the context of such rules is not always a Perfect Divine Creation, and in the case of HTML, CSS, and JavaScript I think that fact is glaringly clear. In such an imperfect environment, hard-line rules can force you into unnecessary work and code that's actually harder to maintain.
edit — oh here's something else I just thought of; sort-of a compromise. A "trick" popularized (in part) by the jQuery gang with their "micro template" facility (apologies to the web genius who actually hit upon this first) is to use <script> tags that are sort-of "neutered":
<script id='pageData' type='text/plain'>
{
'companyName': '<%= company.name %>',
'accountType': '<%= user.primaryAccount.type %>',
// etc
}
</script>
Now the browser itself will not even execute that script - the "type" attribute isn't something it understands as being code, so it just ignores it. However, browsers do make the content of such scripts available, so your code can find the script by "id" value and then, via some safe JSON library or a native browser API if available, parse the notation and extract what it needs. The values still have to be properly quoted etc, but you're somewhat safer from XSS holes because it's being parsed as JSON and not as "live" full-blown JavaScript.
The reason for doing this was so that the developer did not have to define the constant in two places.
To me, this is a better argument than any argument you can make against it. It is the DRY principle. And it greatly enhances code maintainability.
Every style guide/rule taken to extreme leads to an anti-pattern. In this case your insistence of separation of technology breaks the DRY principle and can potentially make code harder to maintain. Even DRY itself if taken to extreme can lead to an anti-pattern: softcoding.
Code maintainability is a fine balance. Style guides are there to help maintain that balance. But you have to know when those very guides help and when they themselves become a problem.
Note that in the example you have given the code would not break syntax hilighting or parsing (even stackoverflow hilights it correctly) so the IDE argument would not work since the IDE can still parse that code correctly.
it simply gets unreadable. You have to take a closer look to divide the different languages. If JavaScript and the mixed-in language use the same variable names, things are getting even worse. This is especially hard for people that have to look at others people code.
Many IDEs have problems with syntax highlighting of heavily mixed documents, which can lead to the loss of Auto-Completion, proper Syntax Highlighting and so on.
It makes the code less re-usable. Think of a JavaScript function that does a common task, like echoing an array of things. If you separate the JavaScript-logic from the data it's iterating over, you can use the same function all over your application, and changes to this function have to be done only once. If the data it's iterating over is mixed with the JavaScript output loop you probably end up repeating the JavaScript code just because the mixed in language has an additional if-statement before each loop.

Categories

Resources