Sunday, September 5, 2010

Creating a standalone executable jar with Scala and SBT

Executable jars (you know, the kind you run java -jar on) are a great way to distribute a compiled program. With Scala it's a little more complicated since the Scala library must be included. And with SBT it's more complicated yet.

Fortunately there's the sbt-proguard-plugin to simplify the task. Proguard is normally used to remove unused code from a project to minimize the size of the resulting jar. But as a side effect it does create a functioning executable jar.

There's very little documentation out there for the plugin, so here's how I got it working.

Step 1) Edit your Project.scala (normally project/build/Project.scala).

Can’t see the code?


Step 2) Edit your Plugins.scala (you may need to create it as plugins/Plugins.scala).

Can’t see the code?


Step 3) Create the jar!
Fire up SBT by running sbt, then do:
reload
update
proguard

That should produce an executable jar target/scala_X.X.X/my-project-X.X.min.jar. Make sure you use the jar with min in its name.

You should now be able the run java -jar my-project-X.X.min.jar on any system with Java installed.

2 comments:

  1. Works perfectly for me, thanks a lot!
    ReplyDelete
  2. For future reference I recommend people just clone my sbt prototype project, which I use regularly and keep up to date: https://github.com/ymasory/sbt-prototype
    ReplyDelete