javascriptvalidationeslintesprima

Validate JavaScript code without enforcing a specific style


I would like to validate some JavaScript code for syntactic correctness, but without enforcing a specific coding-style to the user.

My first approach was to use esvalidate that comes included with esprima. This does the job partially, as it detects unexpected tokens, such as:

constx foo = {};

What it does not detect is among other things usage of variables that have never been declared, such as:

const foox = {
  bar() {}
};

foo.bar();

A tool such as eslint would detect this, but it's very difficult to configure ESLint in a way that no specific style is enforced to the user (I don't say it's not possible, I just say it's a huge amount of work since you need to check every single rule and decide whether to enable or disable it, and with hundreds of rules this is… yes, well, a huge amount of work).

What other options do I have? How could I validate the code without this effort?

By the way: What is it that I want to validate here? It's not the syntax (I mean, syntactically, everything is fine, it just does not make sense), but it's also not the semantics. What would be the correct term for this type of checks?


Solution

  • Years ago Linters were only there to check the style of your code. Nowadays they do more, a lot more. Even static analysis. ESLint is such a powerful tool and IMHO it is exactly what you're looking for.

    You may think the initial configuration may be costly, but as the ESLint page says:

    No rules are enabled by default.

    Besides, having a consistent coding style across your time is very beneficial and if you and your team found a common basline you can share the .eslintrc between projects.

    Enabling the no-undef rule and using a plugin for your IDE, like one of those should solve your issue -> static code analysis at development time :)