Sbt 将设置放在文件中或多项目的 commonSettings 中有什么区别

Sbt what is the difference placing settings in the file or in commonSettings in multi project

初学者问题,我有一个多项目sbt文件,如果我把通用设置放在文件的开头会有什么不同吗?例如:

organization := "com.example"
  version := "0.0.1-SNAPSHOT"
  scalaVersion := "2.11.12"
resolvers ++= Seq(
    "Apache Development Snapshot Repository" at "https://repository.apache.org/content/repositories/snapshots/",
    "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",

    Resolver.mavenLocal
  )
assemblyMergeStrategy in assembly := {
    case PathList("META-INF", xs @ _*) => MergeStrategy.discard
    case x => MergeStrategy.first
  }
lazy val commonSettings  = Seq(  libraryDependencies ++= commonDependencies ++ testingDependencies)
lazy val sharedProject = (project in file(...))
.settings(commonSettings: _*)
val projectA = .....dependsOn(sharedPorject)
val projectB = .....dependsOn(sharedPorject)

或者如果我把它放在常用设置里

lazy val commonSettings  = Seq(  
organization := "com.example",
  version := "0.0.1-SNAPSHOT",
  scalaVersion := "2.11.12",
resolvers ++= Seq(
    "Apache Development Snapshot Repository" at "https://repository.apache.org/content/repositories/snapshots/",
    "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    Resolver.mavenLocal
  ),
assemblyMergeStrategy in assembly := {
    case PathList("META-INF", xs @ _*) => MergeStrategy.discard
    case x => MergeStrategy.first
  },
libraryDependencies ++= commonDependencies ++ testingDependencies)
lazy val sharedProject = (project in file(...))
.settings(commonSettings: _*)
val projectA = .....dependsOn(sharedPorject)
val projectB = .....dependsOn(sharedPorject)

有什么区别?

任何未附加到特定项目设置的定义设置,即 .settings(),都附加到根项目。

这样的代码

organization := "foo"

相同
lazy val root = (project in file(".")).settings(organization := "foo")

现在,如果您定义了一个新的子项目,如 common 并向其添加 organization

lazy val common = (project in file("common")).settings(organization := "bar")

只有它会将值 organization 设置为 bar

当根项目也有自己的 organization 定义时,这将适用于示例。

lazy val root = (project in file(".")).settings(organization := "foo")

lazy val common = (project in file("common")).settings(organization := "bar")

这很容易用命令 sbt "show organization"sbt "show common/organization" 进行测试。它将分别打印 foobar

最后,如果您希望为所有子项目定义相同的值,请在根项目中为范围 ThisBuild 添加设置,如本例所示:

organization in ThisBuild := "foo"

lazy val common = (project in file("common")).settings(???)

或者将设置存储在 Seq 中并将其应用于所有子项目和根。这将具有与范围 ThisBuild 类似的效果,但更明确一点:

val commonSettings = Seq(organization := "foo")

lazy val root = (project in file(".")).settings(commonSettings)
lazy val common = (project in file("common")).settings(commonSettings)