如何在项目中自动 运行 scalafmt?

How can I run scalafmt automatically in project?

我使用 scalafmt plugin in my project, also I use scalafmt plugin for Intellj 来格式化我的 Scala 代码。 通常我使用热键或 运行 sbt scalafmt 来格式化。

sbt.version=1.0.3
addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.3.0")

问题: 关于如何在编译时自动使用 scalafmt 格式化代码的任何建议?

更新: 只需更新插件版本并使用

scalafmtOnCompile := true

下面的答案已经过时了,它建议使用替代插件,但现在是另一种方式,官方是最新的并且开箱即用地支持此功能。

来自 scalafmt installation instructions 您使用的插件:

The sbt plugin does not provide reformat on compile settings. This gist shows a DIY plugin to enable reformat on compile. YMMV.

Why isn't that gist included in the sbt plugin? See #597.

我建议您改用 neo-sbt-scalafmt。它通常更易于配置和更好地维护(其他插件已被放弃,请参阅上面链接的问题)。使用此插件,您可以使用 simple

在编译时打开格式化
scalafmtOnCompile := true

有关更多选项,请参阅 docs