29

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:

vhs
  • 9,316
  • 3
  • 66
  • 70
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
  • 2
    Would be great if VSCode could link an auto-edit to which setting or extension made the edit. As it is, if you have a complex set of formatters, linters, etc. it's basically impossible to figure out the source of a random edit. – ballenf Feb 03 '19 at 15:44
  • Adding a proper `.editorconfig` file in my project solved my issue. – Rubens Mariuzzo Feb 28 '20 at 14:47

4 Answers4

30

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.
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
12

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)
Adarsh Madrecha
  • 6,364
  • 11
  • 69
  • 117
1

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,
vhs
  • 9,316
  • 3
  • 66
  • 70
0

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

Taimoor
  • 67
  • 8