Chetan Bhasin Chetan Bhasin - 1 month ago 9
Scala Question

What is the correct way of using static assets in a Scala SBT project?

What is the best way of using static resources in an SBT based Scala project with a packaging plugin such as

sbt-assembly
or
sbt-native-packager
.

We know that by using TypeSafe-Config with
sbt-native-packager
's universal plugin, we can just put the configuration file in the resources directory under sources. However, what if I wanted my application to have other static sources such as JSON files containing mappings, and models?

I understand that I can just reference the resources directory and read from the file, but would that still work after packaging the application with plugins (assuming the universal or docker plugin in this case)?

If not, what is the correct way to achieve this?

Answer

Put it into the resources directory, but don't "reference the resources directory and read from the file": use ClassLoader.getResourceAsStream() (or getResources, depending on your requirements) instead. This is the same technique TypeSafe Config and innumerable other libraries use. For this it doesn't matter if you use sbt-native-packager or not.

This approach runs into problems if you need to make these resources available specifically as files (e.g. to feed them to an external process). In this case add them to mappings as shown here:

mappings in Universal in packageBin += file("README") -> "README"

(obviously replacing "README" with the file(s) you need).

Comments