sbt类似与maven, gradle的项目管理工具,主要用在scala,也可以用在java项目,本文介绍一下常用的使用命令和语法
安装
- mac
brew install sbt
- redhat¢os
# remove old Bintray repo file
sudo rm -f /etc/yum.repos.d/bintray-rpm.repo
curl -L https://www.scala-sbt.org/sbt-rpm.repo > sbt-rpm.repo
sudo mv sbt-rpm.repo /etc/yum.repos.d/
sudo yum install sbt
快速使用
代码语言:javascript复制➜ mkdir foo-build
➜ cd foo-build
➜ touch build.sbt
➜ foo-build sbt
[info] Updated file /Users/timxia/Workspace/sbt/foo-build/project/build.properties: set sbt.version to 1.3.13
[info] welcome to sbt 1.3.13 (Oracle Corporation Java 1.8.0_251)
[info] loading global plugins from /Users/timxia/.sbt/1.0/plugins
[info] loading settings for project foo-build from build.sbt ...
[info] set current project to foo-build (in build file:/Users/timxia/Workspace/sbt/foo-build/)
[info] sbt server started at local:///Users/timxia/.sbt/1.0/server/7c3ce04c72481c8444dd/sock
sbt:foo-build>
sbt命令
-
sbt
启动,进入交互式命令 -
help
帮助 -
exit
退出sbt -
compile
编译, ~compile自动检测更新后编译 -
run
启动 -
reload
重新加载build.sbt -
session save
保存当前会话信息到build.sbt -
test
执行测试,~testQuick
自动检测并执行测试 -
projects
列出所有项目
build.sbt语法
代码语言:javascript复制# 设置scala版本号
ThisBuild / scalaVersion := "2.13.6"
# 设置项目所属组织
ThisBuild / organization := "com.example"
# 自定义变量
val scalaTest = "org.scalatest" %% "scalatest" % "3.2.7"
## 配置项目hello
lazy val hello = (project in file("."))
# 如果配置了子项目,则聚合起来;父项目上执行的命令,也会广播到子项目
.aggregate(helloCore)
# 设置对子项目的依赖
.dependsOn(helloCore)
.settings(
# 设置项目名称
name := "Hello",
# 添加项目依赖: groupID % artifactID % revision % configuration,这里的configuration类似于maven中的scope,可以Test, Compile
# 如果是scala的库,一般使用%%,这样就会找到对应scala版本的库
libraryDependencies = "org.scalatest" %% "scalatest" % "3.2.7" % Test,
# 如果使用自定义变量,也可以用如下格式
libraryDependencies = scalaTest % Test,
)
## 配置一个子项目helloCore
lazy val helloCore = (project in file("core"))
.settings(
name := "Hello Core",
libraryDependencies = scalaTest % Test,
)
## 覆盖一下jar包
dependencyOverrides = Seq(
"gdt.api" % "gdt-api-aaa" % "1.0.6",
"org.apache.commons" % "commons-compress" % "1.9",
"gdt.api" % "api-client-core" % "2.2.6",
"gdt.api" % "api-client-l5" % "1.1.2",
"gdt.api" % "gdt-api-adservice" % "2.0.75",
"com.alibaba" % "fastjson" % "1.2.67",
"gdt.api" % "gdt-api-customer" % "1.0.69",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.11",
"com.tencent.tdbank" % "TDBusSDK" % "1.2.17",
"gdt.infra" % "infra-l5" % "1.2.7"
)
## 排除一些jar包
excludeDependencies = Seq(
// commons-logging is replaced by jcl-over-slf4j
ExclusionRule("org.slf4j", "slf4j-log4j12")
)
常见问题
- 有时候启动sbt后terminal窗口会停在
Getting org.scala-sbt sbt
上,也不知道发生了什么。可以用如下命令,查看程序进展tail -f $HOME/.sbt/boot/update.log
参考
- sbt by example
- stuck at "Getting org.scala-sbt sbt 0.13.6 ..." when running sbt in terminal