Search code examples
javascalasbtmulti-projectsbt-plugin

How to use sbt plugin as a library dependency in a sbt project?


I have an sbt plugin project that uses multi-project build. I would like to use this plugin as a dependency for the other sbt project. I have created a plugin but when I add this plugin to project, I can't seem to get the dependencies to link up correctly.

sbt-plugin

build.sbt

name := "sbt-plugin"
  sbtPlugin := true
  val commonSettings = Seq(
  organization := "com.example",
  version := "1.0",
  scalaVersion := "2.11.7", 
  javacOptions := Seq("-source", "1.8", "-target", "1.8"), 
  scalacOptions := Seq("-target:jvm-1.8", "-unchecked", "-deprecation", "-encoding", "utf8"))

  lazy val plugin = (project in file("plugin"))
  .settings(commonSettings: _*)
  .settings(
      name := "plugin"
  )

  lazy val root = (project in file("."))
                .settings(commonSettings: _*)
                .dependsOn(plugin)
                .aggregate(plugin)

sbt-plugin\plugin\src\main\scala\com\example\Hello.scala

  package com.example

  // Sample code I would like to access from another sbt project
  object Hello {
     def show = println("Hello, world!")
  }

plugin-test

plugin-test is an sbt project which i used to test sbt-plugin

plugin-test\build.sbt

  name := """plugin-test"""

  version := "1.0"

  scalaVersion := "2.11.7"

  libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.4" % "test"

  fork in run := true

plugin-test\project\plugins.sbt

addSbtPlugin("com.example" % "sbt-plugin" % "1.0", "0.13","2.11")

plugin-test\src\main\scala\com\exam\Test.scala

  package com.exam

  object Test {
     def result = com.example.Hello.show()
  }

But when i compile plugin-test project it shows following errors:

  [error] E:\Play\SBT Plugin\sbt demo1\plugin-test\src\main\scala\com\exam\Test.scala:4: object example is not a member of package com
  [error] def result = com.example.Hello.show()
  [error] one error found

I performed publish-local and plugin/publish-local on both projects and the artifacts resolve correctly. I added sbt-plugin to plugins.sbt and compiled the project but Test.scala fails to compile with the above error, as if the dependency isn't there.

What am I missing here?


Solution

  • When you specify your plugin as addSbtPlugin, you're adding it only to the build environment (i.e. doing things in build.sbt) and not in the classpath of your app (things under src/main/...).

    In your case you need to use it as a regular dependency.