Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davissorenson/a417cfc27322ffffd3ae200b25c7092a to your computer and use it in GitHub Desktop.
Save davissorenson/a417cfc27322ffffd3ae200b25c7092a to your computer and use it in GitHub Desktop.
How to apply VS Code onSave actions (such as organize imports) to every file in a project

How to apply VS Code onSave actions (such as organize imports) to every file in a project

Rationale

Sometimes you want to apply some VS Code onSave action to every file in the project. There are some extensions that claim to do this, but I haven't found any that work. This is a method I discovered, with some help from Stackoverflow of course.

The basic idea is you want to add a superficial change to the start of each file in order to force VS Code to run the onSave actions.

Method

  1. Run a search and replace on the entire project (+Shift+h on macOS or Ctrl+Shift+h on Linux/Windows) using the regex ^(?<![\s\S\r])(.+). Adjust the "files to include" so that all the files you want to run the actions on are included. Explanation:
    • ^(?<![\s\S\r]) uses a failing lookbehind to find the start of a file
    • (.+) matches all the characters on the line.
    • Together, this regex matches all the characters on the first line of every file in the project.
  2. In the replace field, put $1 , which adds a single space to the end of the first line of every file in the project.
  3. Press the "Replace All" button next to the "Replace" field.
  4. Wait while VS Code saves every file in your project. This can take a while, about a minute for ~1,500 TypeScript files on my i9.
  5. While saving each file, VS Code runs all onSave actions, including "organize imports".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment