Cleanup your TypeScript Codebase with clang-format
TypeScript, through its Language Service comes up with a bunch of tools providing some useful features to make the coding experience with it even more productive and less error prone. The code formatting feature does for instance a pretty good job out of the box. But as it’s often the case, relying on standalone tools made for a very specific task (like code formatting) takes us closer to where we want to go.
To install it, just run:
Formatting a file is then as easy as running
Or the entire TypeScript codebase:
The configuration is based on a .clang-format that you need to create. The one I use for my TypeScript projects is pretty simple:
It’ll probably grow over time, but I’m really satisfied by the outcome at the moment.
I’m using the Mozilla guidelines as I’m already using 80 columns max, and two spaces indentation. It also provides a good job reorganising too long lines (better than the Google one in my opinion).
The following line:
Will turn into:
With the Google style, and into:
With the Mozilla one. Of course, you can configure every single behaviour to make it fit 100% your needs, but starting from an existing base makes things a bit smoother.
Another thing also really useful is the cleanup of ES6 import statements. It doesn’t only alphabetically sort the statements, but also separates them into logical chunks (imports from node modules, from modules placed in parents directories, child directories).
For instance, the following code:
Of course, having to run the clang-format command every time we want to cleanup would quickly become a tedious task. Fortunately, there are plugins for most of the text editor out there allowing to do it without having to switch the context (of writing your code).
Using clang-format with Vim
The Vim plugin to bring clang-format integration is called vim-clang-format. After having installed it using your favorite Package manager, you can format the open file by calling the :ClangFormat command (works also within a visual selection):
Using clang-format with Atom
The package allowing the execution of clang-format directly inside Atom is called clang-format. It comes with a predefined key-binding (set to CMD-Shift-K on macOS), calling the clang-format executable under the hood:
Using clang-format with Visual Studio Code
The Visual Studio Code extension for clang-format vscode-clang-format-provider. The nice thing about it, is that it’s directly bound to the built-in code formatting mechanism of Visual Studio Code (Ctrl+Shift+F on Windows/Linux, and Cmd+Shift+F on Mac). It also allows to format automatically while saving a file, to automate the process a bit more, by putting:
in the settings.json file.
Productivity, TypeScript and tagged Atom, clang-format, code formatting, Productivity, typescript, Vim, visual studio code. Bookmark the permalink.