sbt快速入門

sbt類似與maven, gradle的項目管理工具,主要用在scala,也可以用在java項目,本文介紹一下常用的使用命令和語法

安裝

  • mac
brew install sbt
  • redhat&centos
# 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

快速使用

➜ 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語法

# 設置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

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章