使用 vs 代码,如何让 scala 格式工作并格式化我的代码?

Using vs code, how to get scala format to work and format my code?

我的多项目 sbt 存储库中有 scala 格式插件。

addSbtPlugin("org.scalameta"    % "sbt-scalafmt"        % "2.3.2")

所以在 sbt 控制台中,如果我 运行 scalafmt 它工作正常

我的 build.sbt 有:

scalafmtOnCompile := true

如果我在 sbt 中进行 ~compile 或只是手动编译,它不会在编译期间格式化我的代码。

我的设置有什么问题?

此外,运行ning scalafmt 可以工作,但它不会像我的 Dependencies.scala 文件那样格式化 /project 中的 .scala 文件。为什么忽略这些文件?

我将 VS Code 与金属一起用作我的 IDE。

Scalafmt 在我的机器上开箱即用的 Metals 似乎可以在 VSC 中工作

Metals automatically uses Scalafmt to respond to formatting requests from the editor, according to the configuration defined in .scalafmt.conf... if there is no .scalafmt.conf, upon receiving the first format request Metals will create the .scalafmt.conf file for you.

只需在 VSC 中从 Command Palette 执行 Format Document 命令,它应该根据 .scalafmt.conf. 进行格式化 如果您想在每次源更改和 scalafmtOnCompile 不起作用,然后尝试在 sbt

中执行
~scalafmt;compile

但是编译时的格式是 discouraged 根据文档

This option is discouraged since it messes up undo buffers in the editor and it slows down compilation. It is recommended to use "format on save" in the editor instead.

在 VS Code 中,如果您进入 File -> Preferences - > Settings 并输入 editor.format,您会看到一堆选项。

启用所有这些,它的金属应该应用所有相应的更改。