JSLint - ignore sections of code

こ雲淡風輕ζ 提交于 2019-11-28 22:31:55

I think this has already been fixed in JSHint for some time. Simply wrap your code with comments:

/* jshint ignore:start */
// Code here will be linted with ignored by JSHint.
/* jshint ignore:end */

The documentation can be found here and scroll down to the "directives" section.

You can add this yourself to JSLint if you want, though that's borderline Evil.

Here's one quick and dirty way with the current version:

The route I'm going to take is to hijack the token function's switch block for /* style comments. That's at line 1276 currently:

case '/*':
    for (;;) {
        i = source_row.search(lx);
...

Let's change that to look for comments that look like /*ignore:true */ on a line by themselves (although technically the true half can be anywhere on the line in this case, though the /*ignore:false */ line has to be on a line by itself, so let's pretend that holds for both).

Example bad, lint-failing code:

function spam()
{
    var sand = "sand";
/*ignore:true */
    var spud = "spud";
/*ignore:false */
    window.console.log(sand);
}

If we find /*ignore:true */, let's skip lines until we find one with /*ignore:false */ with /*ignore:... as the very first characters on the line. Until that false statement on a line by itself, we ignore everything.

case '/*':
    // Opening /* has already been sliced.
    if (source_row.startsWith("ignore:true"))    {
        do  {
            if (console.log) { console.log(source_row) };
        } while (next_line() && !source_row.trim().startsWith("/*ignore:false"));
    }   else    {
        // Put in the code that was originally there
    }
    break;

That's ugly, but seems to be working.

Now this can cause issues. For example, if you have a var declaration in a section you ignore and use it later, JSLint_Hacked will complain that myVar was used before it was defined. Example:

/*jslint white:true, sloppy:true, browser:true */
function spam()
{
    var sand = "spam";
/*ignore:true */
    var spud = "spud";
/*ignore:false */
    window.console.log(sand + spud);
}

So that kind of stuff could get nasty.

And I'd only use this in cases where you're inanely forced to lint everything, but for some reason you don't have the power to fix what's in every file, though you do have the ability to edit it, strangely, as in this case with obfuscated code. This whole ignore thing is waaay seedy.

I need to spend more time inside of JSLint to know how it really works, but the next_line() function seems to be non-destructive. That is, you could (and should) handle this in the do_jslint() function with "real" /*jslint ignore:true */ style directives, but then you have to handle side effects when you call the advance() function. The hack I'm using here was much easier, but is also much uglier.

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