How to share resources between projects in SBT

2019-02-18 00:02发布

问题:

The project I'm working on at work is a webapp on the Lift Framework. We're using xsbt web plugin as well. There's a "core" project, which contains the vast majority of the functionality; my current goal is to create two "distribution" projects that add a different set of classpath resources to the "core" project. The problem is that I either 1) can't get the "distribution" projects to run, or 2) Get them to run, but the required resource doesn't seem to be there.

What I've tried

Here's an abridged version of my project/Build.scala:

lazy val core = Project("Core", file("core"))
  .settings( /*some dependencies, resolvers, webSettings */ )

lazy val app1 = Project("App1", file("app1"))
  .aggregate(core)
  .settings( /*the same settings as core */ )

lazy val app2 = Project("App2", file("app2"))
  .aggregate(core)
  .settings( /*the same settings as core*/ )

Then in the directory structure for both app1 and app2, I have a file at src/main/resources/aFileINeed. The core application is using the class.getResource approach to load the file from the classpath.

Problems

If I try to run one of the distribution projects, using container:start, it does not detect the required file in the classpath. Also, it claims that src/main/webapp is not an existing directory (that folder is included in the core project, as it is required by the xsbt web plugin).

How can I get these projects to "merge" their resources? I expected that using aggregate or dependsOn in the Build.scala project definition would handle that for me, but it apparently doesn't.

回答1:

This is what I'm doing. I create a global 'resources' directory in the root of the project, and then the following variable:

    lazy val globalResources = file("resources")

And then in every project's settings:

    unmanagedResourceDirectories in Runtime += globalResources 

For projects that use the xsbt-web-plugin or some other library that imports it you'll have to use the stronger

    unmanagedResourceDirectories in Compile += globalResources

Beware that using this solution your projects will potentially have muliple resource directories and AFAIK if you define the same file twice compile:copy-resources is going to be angry at you.