简体   繁体   English

如何使用eslint格式化我的javascript代码?

[英]How to use eslint to format my javascript code?

I'm using vim as my editor, I use eslint for linting javascript code. 我使用vim作为我的编辑器,我使用eslint来绘制javascript代码。 Before, I use js-beautify for formatting js code. 之前,我使用js-beautify格式化js代码。 But recently I found that eslint has a --fix option, which can fix normal coding style issue violate eslint rules. 但最近我发现eslint有一个--fix选项,它可以修复正常的编码风格问题,违反了eslint规则。

I also find this post which suggests use eslint for code formatting. 我也发现这篇文章建议使用eslint进行代码格式化。 I feel it's a great idea, because I find it's kind of redundant to have both eslint and js-beautify. 我觉得这是一个好主意,因为我发现同时拥有eslint和js-beautify是多余的。 Since eslint can already detects all my coding style issues, why can't it do format for me? 由于eslint已经可以检测到我的所有编码风格问题,为什么它不能为我格式化?

there's also one drawback to have both js-beautify and eslint, that I need to adjust js-beautify to be in accordance with eslint rules. 同时拥有js-beautify和eslint也有一个缺点,我需要调整js-beautify以符合eslint规则。 This is completely unnecessary. 这完全没必要。

But when I use eslint --fix to js file, it only do some fixing like: insert semicolon, add some space where necessary. 但是当我使用eslint --fix到js文件时,它只做一些修复:插入分号,在必要时添加一些空格。 But if my code is compressed, it won't format it nicely to human readable format. 但是如果我的代码被压缩了,它就不会很好地格式化为人类可读的格式。

How can I make eslint do code format as js-beautify does? 我怎么能像js-beautify一样制作eslint代码格式呢?

I didn't really make eslint format code. 我没有真正制作eslint格式代码。 But a trick can be used is to pipe the result of js-beautify to eslint --fix . 但是可以使用的技巧是将js-beautify的结果传递给eslint --fix Thus multiple statements on same line will be formatted by js-beautify and the result will be sent to eslint --fix to fix normal style issues, in the end, you get the formatted and fixed version of code. 因此,同一行上的多个语句将由js-beautify格式化,结果将被发送到eslint --fix以修复正常的样式问题,最后,您将获得格式化和固定版本的代码。

Not all rules can be automatically fixed. 并非所有规则都可以自动修复。 Sometimes, it's important for a human to decide how to correct a problem. 有时候,决定如何纠正问题对于人类来说很重要。 These rules won't be fixed for you. 这些规则不适合您。

Other rules, like trailing commas, can be safely fixed automatically, and are applied with --fix . 其他规则(如尾随​​逗号)可以自动安全地修复,并使用--fix进行应用。

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

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