Cyril Gandon
Cyril Gandon

Reputation: 17068

Prevent VSCode auto format on save from removing final newline

I am using the last feature of VSCode called formatOnSave, which is super cool.
I have one tiny problem, the formatter tends to delete the new line at the end of json files like packages.json for example.

My linter want those new lines at the end of the file, and me too.

Is there a setting or a method that allows me to tell the formatter to keep new lines at the end of files?

Related issue:

Upvotes: 32

Views: 22460

Answers (4)

Taimoor
Taimoor

Reputation: 81

In my case, I just changed the prettier.endOfLine setting from cr to crlfin VS code settings JSON enter image description here

Upvotes: 0

Adarsh Madrecha
Adarsh Madrecha

Reputation: 7946

If you wish to preserve the last line in package.json and not affect other file types, add below lines to your vs code configuration.

  "[json]": {
    "files.insertFinalNewline": true,
    "files.trimFinalNewlines": true,
  }

This basically tells VS code to

  1. Apply settings only to json files
  2. Insert final lines at end of the file
  3. Remove extra lines at the end of the file (i.e. only keep 1 empty line)

Upvotes: 17

vhs
vhs

Reputation: 10089

My linter want those new lines at the end of the file, and me too.

VSCode ESLint has an option called autoFixOnSave you could try. Depending on your workflow ESLint CLI also has a --fix option you could tie into a git hook.

If you're just looking for some sensible defaults here they are:

"files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,

Upvotes: 2

Cyril Gandon
Cyril Gandon

Reputation: 17068

This option has been added since the release 1.8 of November 2016:

New editor settings

  • files.insertFinalNewline - automatically add a newline at the end of files when saving.

Upvotes: 34

Related Questions