Prevent deleting dead code during Auto Format on Save?

Viewed 976

What is the magic configuration for allowing a file to be auto-formatted upon a Save operation, but stop / disable / prevent VSCode from deleting dead code?

Sometimes I want to deliberately throw an exception in the middle of a function, for debugging purposes but am forced to comment out all following code in order not to get it deleted.

What's worse is that sometime I save while the editor didn't yet recover from some error in the code, thinks the code still contains an error, and causes code deletions which should not happen in the first place. I found myself too many times pulling up git in order to restore good code which was wrongly deleted.

Is there a clear "do not delete dead code" option to switch on?

UPDATE:

  1. Running Prettier (the file's formatter) from command line did not delete dead code.
  2. Trying to disable all extensions didn't help either. The dead code is still deleted upon save.
2 Answers

Case solved.

I can't pinpoint the exact package that's causing it but it seems to be related to either ESLint or Prettier.

Turns out that the project's Github repo contains a .vscode directory with a settings.json that contains the following configuration:

{
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  }
}

I already saw posts saying to add "source.fixAll": false to VSCode's general settings.json file, but it had no effect when I did.

Setting the flag to false did the trick

{
  "editor.codeActionsOnSave": {
    "source.fixAll": false
  }
}

Note: Adding the above block to the general settings.json had no effect as well. I had to modify the local .vscode/settings.json file to get it to work.

I will just share what I found on Github here,

So if you replace your codeActionsOnSave and use eslint it should prevent vscode from running fixes on the rule eslint(no-unreachable) and delete your code on save (probably because another formatter like Prettier runs its fix on that).

settings.json

{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}

source: https://github.com/microsoft/vscode-eslint/issues/833

Related