创建新的构建

要使用 sbt 开始新的构建,请使用 sbt new

$ mkdir /tmp/foo
$ cd /tmp/foo
$ sbt new

Welcome to sbt new!
Here are some templates to get started:
 a) scala/toolkit.local               - Scala Toolkit (beta) by Scala Center and VirtusLab
 b) typelevel/toolkit.local           - Toolkit to start building Typelevel apps
 c) sbt/cross-platform.local          - A cross-JVM/JS/Native project
 d) scala/scala3.g8                   - Scala 3 seed template
 e) scala/scala-seed.g8               - Scala 2 seed template
 f) playframework/play-scala-seed.g8  - A Play project in Scala
 g) playframework/play-java-seed.g8   - A Play project in Java
 i) softwaremill/tapir.g8             - A tapir project using Netty
 m) scala-js/vite.g8                  - A Scala.JS + Vite project
 n) holdenk/sparkProjectTemplate.g8   - A Scala Spark project
 o) spotify/scio.g8                   - A Scio project
 p) disneystreaming/smithy4s.g8       - A Smithy4s project
 q) quit
Select a template:

如果您选择 "a",您将会收到更多问题的提示:

Select a template: a
Scala version (default: 3.3.0):
Scala Toolkit version (default: 0.2.0):

按回车键选择默认值。

[info] Updated file /private/tmp/bar/project/build.properties: set sbt.version to 1.9.8
[info] welcome to sbt 1.9.8 (Azul Systems, Inc. Java 1.8.0_352)
....
[info] set current project to bar (in build file:/private/tmp/foo/)
[info] sbt server started at local:///Users/eed3si9n/.sbt/1.0/server/d0ac1409c0117a949d47/sock
[info] started sbt server
sbt:bar> exit
[info] shutting down sbt server

以下是此模板创建的文件:

.
├── build.sbt
├── project
│   └── build.properties
├── src
│   ├── main
│   │   └── scala
│   │       └── example
│   │           └── Main.scala
│   └── test
│       └── scala
│           └── example
│               └── ExampleSuite.scala
└── target

让我们看一下 build.sbt 文件:

val toolkitV = "0.2.0"
val toolkit = "org.scala-lang" %% "toolkit" % toolkitV
val toolkitTest = "org.scala-lang" %% "toolkit-test" % toolkitV

scalaVersion := "3.3.0"
libraryDependencies += toolkit
libraryDependencies += (toolkitTest % Test)

这被称为构建定义,它包含 sbt 编译项目所需的信息。这是用 .sbt 格式编写的,它是 Scala 语言的一个子集。

以下是 src/main/scala/example/Main.scala 中的内容:

package example

@main def main(args: String*): Unit =
  println(s"Hello ${args.mkString}")

这是一个 Hello world 模板。我们可以通过启动 sbt --client 并在 shell 中输入 run <您的名字> 来从 sbt shell 运行它:

$ sbt --client
[info] entering *experimental* thin client - BEEP WHIRR
[info] server was not detected. starting an instance
....
info] terminate the server with `shutdown`
[info] disconnect from the server with `exit`
sbt:bar> run Raj
[info] running example.main Raj
Hello Raj
[success] Total time: 0 s, completed Feb 18, 2024 2:38:10 PM

Giter8 模板

除了几个 .local 模板外,sbt new 还与 Giter8 集成,这是一个使用 GitHub 托管模板的开放模板系统。例如,scala/scala3.g8 由 Scala 团队维护,用于创建新的 Scala 3 构建:

$ /tmp
$ sbt new scala/scala3.g8

Giter8 wiki 列出了 100 多个可以快速启动您新构建的模板。