简体   繁体   中英

How to discriminate JSON code formatting by removing empty lines using Eslint + Prettier

BACKGROUND

When creating test files there is normally a lot of copy and paste of JSON objects (even if you use your own factories). I find that if you modify schema sometimes it easier to find and replace on the key + pair. The issue is that the find and replace in IDE's (unless you can customize it ... VSCode, Intellij, etc.?) will not do a auto post-save cleanup if what you replaced originally produces a empty line in the JSON object.


ASK

Is there a way to configure eslint and/or prettier that on auto save it will condense your JSON objects by removing empty lines?

(If not, does anybody have a regex that can differentiate between code blocks / closures vs. JSON objects and remove any blank lines?)


EXAMPLE: JSON Objects in JavaScript Files

Before Formatting

const blah = {
   EffectiveDate: '2019-01-01',
   DiscontinueDate: '2019-12-12',

   MarkDownCode: 'W'
}

After Formatting

const blah = {
   EffectiveDate: '2019-01-01',
   DiscontinueDate: '2019-12-12',
   MarkDownCode: 'W'
}

As far as I can tell you can only set prettier to condense multiple sequential empty lines into one empty line.

What you can do, though, is use any text editor with a Find&Replace functionality that accepts a Regex expression and then replacing:

^\\n

for an empty string:

''

Usually the Find&Replace can be opened using Ctrl+H .

Additionally, I would add that if you were so inclined to achieve automation of this task you could look into extensions for your code editor that allows some type of "Run on Save" functionality and then adding a little script to erase those new lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM