Fix sort-keys ESLint rule in VSCode - javascript

I am using Visual Studio Code for my front end development. I have enabled the sort-keys rule which requires the keys of all object to be in alphabetical order.
I came to find out that neither ESLint, nor Prettier supports autofixing it, due to potential bugs the auto-fix can introduce, thus both of them has rejected the proposal to even consider adding auto-fix as option.
Now I have a very large legacy code base where I just added ESLint, and I need this sort-keys rule in the project. Is there any way I can auto-fix them provided I know what am I doing, possibly through some VSCode plugin or a custom script?
I am sure that changing the order of the keys will not affect my code negatively. I need it for both JSON objects as well as JS object literals.

Not exactly an automated solution but it helps with sorting object keys manually during development.
Sort JS object keys VS Code plugin
Install the plugin
Select an object in the code, including outer { and }. Hint: expand selection keyboard shortcut ⌃⇧⌘→ is helpful for this.
Run "Sort JS object keys" command.

Related

ESlint: Highlighting ES6 code in an non-transpiled ES5 codebase

We currently have a problem with our build pipeline that prevents certain parts of our legacy codebase from being transpiled.
Subsequently parts of our codebase have to be written in ES5 in order to be backwards compatible with older browsers.
The problem we're having is enforcing the use of ES5 code within these legacy scripts. There are a lot of places in the code where ES6 features (let, const, destructuring, object shorthand) are already used.
Adding an eslint config with the ecmaVersion set to 5 is not ideal because of the way the parser throws an exception on reaching an es6 feature, subsequently meaning no additional linting of the file happens. So you need to resolve all es6 type exceptions before this becomes an option.
We are unable to undertake a grand refactor of the code like this at present. As some parts are still being actively worked on. It is, in a word, a sh*tshow.
My question is, short of building some custom eslint plugin that highlights es6 features, is there any other solution that I may have missed?
As per #VLAZ' suggestion
https://github.com/nkt/eslint-plugin-es5
using the following config in eslintrc:
{
"plugins": [
"es5"
]
}
Worked perfectly for what we needed it for.

ESLint: Environment-specific rules [duplicate]

I am collaborating on a git-sourced, maven-managed Java project with differing code styling preferences with users using multiple IDE's (note 1).
Is there a tool or IDE configuration that will allow code to be viewed and edited using style-1, but committed to SCM using style-2?
My research points me to 'no', but a solution combining git hooks and Checkstyle/jrefactory might be possible.
So if 'no' to above, is there a tool/process that will perform the TBD process actions below?
The checkout process flow for User1 would be:
git pull
TBD process formats code to User1 style-1
User1 works in their preferred IDE with style-1 settings
The commit workflow for User1 would be:
User1 is ready to commit/push code
TBD process formats code to standard format style-standard
git push
Note 1: multiple IDE's = Eclipse, IntelliJ, Netbeans.
Note 2: My question differs from this question in that I'd like to focus on an IDE-related solution, since forcing the minority of standards-divergent users is probably a more efficient solution.
Note 3: Acknowledging that this shouldn't be done for best-practices-reasons. However, if you grant that it's time expect more flexibility from our IDEs and SCMs, this question is intended to explore those solutions.
First of all, you really shouldn't do that. Codestyle wars are bad for any project, and it is best to decide upon one codestyle that everybody must use. It is simple to configure IDEs to automatically apply the specified codestyle at every filesave, so the developers don't have to write code in the target codestyle themselves, they can let the IDE do that for them. True, this doesn't solve the fact that they'll have to read code in a codestyle they don't yet like, but it's a lot safer than having invisible automatic code changes; that's a major source of bugs.
Maybe you can use Eclipse's code formatter from the command line to apply a different codestyle. You'd have to set up git hooks, make sure everybody has Eclipse available, and provide the proper configuration files for their preferred codestyle. You'd need hooks both for post-checkout and pre-commit, one to set up the user's codestyle, the other to commit in the central codestyle. To go one step further, you can play with the index to add the formatted code so that it doesn't include style differences in git diff (although they will show up in git diff --staged).
Again, you shouldn't do that.
I agree with Sergiu Dumitriu in this not being a very good idea. But still git provides exactly what you are looking for. Even though this will only work if your central coding style is very well defined and strictly followed. Here’s how it works:
Git provides smudge/clean filters. They allow you to pass all code through a so-called “smudge” filter on checkout and reverse that with a “clean” filter when code is added to the staging area. These filters are set in .gitattributes, and there is a repository-local version of that file available in .git/info/attributes.
So you set your smudge filter to a tool that will change the code to your personal coding style on checkout:
And your clean filter will convert the code back to the central coding style on checkin (more precisely: when file are staged):
It is very important, that smudge -> clean is a no-op / generates the original file again. Otherwise you will still check in format changes every time you change a file.
Using smudge and clean filters will retain all the functionality of git (including git diff etc). You can find the full docu in git help attributes

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.

How can I set the language_in option for the Closure compiler?

I need to set the language_in option on the Closure compiler to prevent the IE8 parse error:
ERROR - Parse error. IE8 (and below) will parse trailing commas in array and object literals incorrectly. If you are targeting newer versions of JS, set the appropriate language_in option.
I did find a post in the closure group relating to this, however, the option is set directly on the java compiler, rather than through one of the build scripts. I need to be able to set it on a build script.
I'm looking at the scripts in closure/bin/build/ and there are several there. I tried adding the option to closure builder, but it failed.
Can someone direct me about how to set this option correctly?
Thank you.
Run the Closure Compiler Application with the --help flag to see a description of each flag.
java -jar compiler.jar --help
CommandLineRunner defines the set of allowed values for --language_in:
--language_in
Sets what language spec that input sources conform.
Options: ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT5_STRICT,
ECMASCRIPT6_TYPED (experimental), ECMASCRIPT_2015, ECMASCRIPT_2016,
ECMASCRIPT_2017, ECMASCRIPT_NEXT
The LanguageMode enum has a bit more detail about these values.
Using Closure Builder, the --language_in flag would be passed as an argument to
--compiler_flags as in:
--compiler_flags="--language_in=ECMASCRIPT5"

JavaScript dependency management

I am currently maintaining a large number of JS files and the dependency issue is growing over my head. Right now I have each function in a separate file and I manually maintain a database to work out the dependencies between functions.
This I would like to automate. For instance if I have the function f
Array.prototype.f = function() {};
which is referenced in another function g
MyObject.g = function() {
var a = new Array();
a.f();
};
I want to be able to detect that g is referencing f.
How do I go about this? Where do I start? Do I need to actually write a compiler or can I tweak Spidermonkey for instance? Did anyone else already do this?
Any pointers to get me started is very much appreciated
Thanks
Dok
Whilst you could theoretically write a static analysis tool that detected use of globals defined in other files, such as use of MyObject, you couldn't realistically track usage of prototype extension methods.
JavaScript is a dynamically-typed language so there's no practical way for any tool to know that a, if passed out of the g function, is an Array, and so if f() is called on it there's a dependency. It only gets determined what variables hold what types at run-time, so to find out you'd need an interpreter and you've made yourself a Turing-complete problem.
Not to mention the other dynamic aspects of JavaScript that completely defy static analysis, such as fetching properties by square bracket notation, the dreaded eval, or strings in timeouts or event handler attributes.
I think it's a bit of a non-starter really. You're probably better of tracking dependencies manually, but simplifying it by grouping related functions into modules which will be your basic unit of dependency tracking. OK, you'll pull in a few more functions that you technically need, but hopefully not too much.
It's also a good idea to namespace each module, so it's very clear where each call is going, making it easy to keep the dependencies in control manually (eg. by a // uses: ThisModule, ThatModule comment at the top).
Since extensions of the built-in prototypes are trickier to keep track of, keep them down to a bare minimum. Extending eg. Array to include the ECMAScript Fifth Edition methods (like indexOf) on browsers that don't already have them is a good thing to do as a basic fixup that all scripts will use. Adding completely new arbitrary functionality to existing prototypes is questionable.
Have you tried using a dependency manager like RequireJS or LabJS? I noticed no one's mentioned them in this thread.
From http://requirejs.org/docs/start.html:
Inside of main.js, you can use require() to load any other scripts you
need to run:
require(["helper/util"], function(util) {
//This function is called when scripts/helper/util.js is loaded.
//If util.js calls define(), then this function is not fired until
//util's dependencies have loaded, and the util argument will hold
//the module value for "helper/util".
});
You can nest those dependencies as well, so helper/util can require some other files within itself.
As #bobince already suggested, doing static analysis on a JavaScript program is a close to impossible problem to crack. Google Closure compiler does it to some extent but then it also relies on external help from JSDoc comments.
I had a similar problem of finding the order in which JS files should be concatenated in a previous project, and since there were loads of JS files, manually updating the inclusion order seemed too tedious. Instead, I stuck with certain conventions of what constitutes a dependency for my purposes, and based upon that and using simple regexp :) I was able to generated the correct inclusion order.
The solution used a topological sort algorithm to generate a dependency graph which then listed the files in the order in which they should be included to satisfy all dependencies. Since each file was basically a pseudo-class using MooTools syntax, there were only 3 ways dependencies could be created for my situation.
When a class Extended some other class.
When a class Implemented some other class.
When a class instantiated an object of some other class using the new keyword.
It was a simple, and definitely a broken solution for general purpose usage but it served me well. If you're interested in the solution, you can see the code here - it's in Ruby.
If your dependencies are more complex, then perhaps you could manually list the dependencies in each JS file itself using comments and some homegrown syntax such as:
// requires: Array
// requires: view/TabPanel
// requires: view/TabBar
Then read each JS file, parse out the requires comments, and construct a dependency graph which will give you the inclusion order you need.
It would be nice to have a tool that can automatically detect those dependencies for you and choose how they are loaded. The best solutions today are a bit cruder though. I created a dependency manager for my particular needs that I want to add to the list (Pyramid Dependency Manager). It has some key features which solve some unique use cases.
Handles other files (including inserting html for views...yes, you can separate your views during development)
Combines the files for you in javascript when you are ready for release (no need to install external tools)
Has a generic include for all html pages. You only have to update one file when a dependency gets added, removed, renamed, etc
Some sample code to show how it works during development.
File: dependencyLoader.js
//Set up file dependencies
Pyramid.newDependency({
name: 'standard',
files: [
'standardResources/jquery.1.6.1.min.js'
]
});
Pyramid.newDependency({
name:'lookAndFeel',
files: [
'styles.css',
'customStyles.css',
'applyStyles.js'
]
});
Pyramid.newDependency({
name:'main',
files: [
'createNamespace.js',
'views/buttonView.view', //contains just html code for a jquery.tmpl template
'models/person.js',
'init.js'
],
dependencies: ['standard','lookAndFeel']
});
Html Files
<head>
<script src="standardResources/pyramid-1.0.1.js"></script>
<script src="dependencyLoader.js"></script>
<script type="text/javascript">
Pyramid.load('main');
</script>
</head>
It does require you to maintain a single file to manage dependencies. I am thinking about creating a program that can automatically generate the loader file for you based on includes in the header but since it handles many different types of dependencies, maintaining them in one file might actually be better.
JSAnalyse uses static code analysis to detect dependencies between javascript files:
http://jsanalyse.codeplex.com/
It also allows you to define the allowed dependencies and to ensure it during the build, for instance. Of course, it cannot detect all dependencies because javascript is dynamic interpretet language which is not type-safe, like already mentioned. But it at least makes you aware of your javascript dependency graph and helps you to keep it under control.
I have written a tool to do something like this: http://github.com/damonsmith/js-class-loader
It's most useful if you have a java webapp and you structure your JS code in the java style. If you do that, it can detect all of your code dependencies and bundle them up, with support for both runtime and parse-time dependencies.

Categories

Resources