I can’t tell you how many times I’ve committed and pushed some code changes only to realize or have a colleague point out that my changes introduced trailing whitespace. This happened all too frequently until I recently adopted some tools and practices to keep my whitespace in check. Turns out it’s pretty easy to remove whitespace from code changes.
IDE Configuration
I’m a VS Code user, and a big fan of that IDE (Integrated Development Environment). If you don’t already use a particular IDE, I recommend checking it out.
Whichever IDE you use, there should be a setting or configuration to show all whitespace right in your editor. For VS Code users, here’s how to activate this feature:
- With VS Code open, navigate to Code > Preferences > Settings (on Mac, on Windows this is File > Preferences > Settings)
- In the Settings panel you should see a search bar. Here you can search for ‘Render whitespace’ and the top result should be ‘Editor: Render Whitespace’. In the dropdown menu here, select ‘all’. You could also select ‘trailing’ to see only the trailing whitespace, but my preference is to see all whitespace flagged.
Project Settings
If your current project has a .vscode > settings.json file for handling settings specific to that project, you can optionally set a whitespace configuration there by adding the following:
{
"editor.renderWhitespace": "all",
}
Check The Git Diff
The moment that you’re ready to commit some work is a great time to stop and check the git diff
of your work. Not only can this help you catch accidental or erroneous code changes, it’s also an easy way to see if you’ve introduced any unwanted whitespace changes.
The screenshot above is from some actual code I wrote for this site, and the red blocks each indicate whitespace changes (which I ended up removing).