简体   繁体   English

如何通过使用Eslint + Prettier删除空行来区分JSON代码格式

[英]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). 创建测试文件时,通常会有很多JSON对象的副本和粘贴(即使您使用自己的工厂)也是如此。 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. 问题是,如果您最初替换的内容在JSON对象中产生了空行,则在IDE中进行查找和替换(除非您可以对其进行自定义... VSCode,Intellij等?)将不会自动执行保存后的清理。


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? 有没有一种方法可以配置eslint和/或prettier ,以便在自动保存时通过删除空行来压缩JSON对象?

(If not, does anybody have a regex that can differentiate between code blocks / closures vs. JSON objects and remove any blank lines?) (如果没有,是否有人可以使用正则表达式区分代码块/闭包与JSON对象,并删除任何空白行?)


EXAMPLE: JSON Objects in JavaScript Files 示例:JavaScript文件中的JSON对象

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 . 通常,可以使用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. 另外,我还要补充一点,如果您愿意实现此任务的自动化,则可以查看代码编辑器的扩展,这些扩展允许某种类型的“运行时保存”功能,然后添加一个小脚本来删除这些新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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