Typescript with Play Framework

Because types are cool…

It seems weird that coffeescript is in all the demos for a company recently known as typesafe. I use Typescript on the frontend where possible.

sbt-typescript was maintained in two projects ArpNetworking/sbt-typescript and joost-de-vries/sbt-typescript. But neither has been updated in a long time.

I have forked and updated to the latest Typescript 3+. If you want all the niceness of types on your frontend code when using Play Framework, check out:

https://github.com/platypii/sbt-typescript

addSbtPlugin("com.github.platypii" % "sbt-typescript" % "3.7.5")

3 Likes

I wouldn’t bother with sbt plugins for doing javascript work.
I added package.json + webpack + ts-loader to my project and have full power over typescript and any other more modern frontend tech you want to use.

I created a play run webhook (which triggers webpack file watching when running play in development mode)

in foo/project/webpack.scala

import sbt._
import play.sbt.PlayRunHook
import scala.sys.process.Process

object Webpack {
  def apply(base: File): PlayRunHook = {
    
    object WebpackProcess extends PlayRunHook {
      var process: Option[Process] = None

      override def beforeStarted(): Unit = {
        process = Some(Process("npm run start", base).run)
      }

      override def afterStopped(): Unit = {
        process.map(p => p.destroy())
        process = None
      }
    }
    WebpackProcess
  }
}

in foo/webpack.config.js

// to support hot reloading in development mode, files are written to sbt-web folder.
// for a production build, files are written to a folder which is configured
// to be bundled into the public assets folder.
function getOutputPath(mode) {
  const dir = (mode === 'production') ? 'target/webpack/js' : 'target/web/public/main/js';
  return path.resolve(__dirname, dir);
}

in foo/build.sbt

// add development mode run hook which starts webpack file watcher (./project/webpack.scala)
PlayKeys.playRunHooks += Webpack(baseDirectory.value)
// include webpack output js files in the public assets
Assets / unmanagedResourceDirectories += target.value / "webpack"

in foo/package.json

scripts: {
  "start": "webpack --config webpack.config.js --mode=development --watch"
}
1 Like