I've tried different solutions, from regular expressions in Sublime Text to
dedicated JavaScript beautifiers such as js-beautify and UglifyJS2 (with the --beautify
option). Regarding regex, it seemed too complicated to find an expression that could cover all the cases you mentioned, while for the other two tools, they look good, but even with specific options, they changed more than just indentation and needed some extra work for bulk processing.
In the end, the tool I suggest to use is Artistic Style (a.k.a. AStyle):
Artistic Style is a source code indenter, formatter, and beautifier
for the C, C++, C++/CLI, Objective‑C, C# and Java programming
languages.
It's a command line tool, free, open-source (here's the SourceForge page), cross-platform, well-documented and easy to setup and configure. It's not specific to JavaScript, but for what I could test it works well with that programming language too. The bulk processing is a feature of the program.
Here are some use cases based on your requirements:
From tabs to spaces: AStyle.exe C:\tmp\*.js --indent=spaces=2
From spaces to tabs: AStyle.exe C:\tmp\*.js --indent=force-tab
From 2 spaces to 4 spaces: AStyle.exe C:\tmp\*.js --indent=spaces=4
More options are available to:
- prevent the creation of a backup file
- run recursively in all subdirectories
- perform a dry run
- apply several code formattings, not just indentation
- etc.
In addition, on the website, you can have a look at the page dedicated to ready-to-use scripts and the list of GUI programs/plugins that use AStyle (among them there's also a Sublime Text plugin, which I haven't tried but I presume it cannot process files in bulk).