John
John

Reputation: 5364

In Play2.x how can I uglify js templates

In one of my Play2.4 application (Scala), I have JS files that are generated via Twirl (the template engine) so I can use internal variables.

Is there a way these JS files can be minified once in Prod?

Upvotes: 3

Views: 182

Answers (2)

Gus
Gus

Reputation: 4517

You can use sbt-uglify for that. First you need to add the plugin to your plugins.sbt file:

addSbtPlugin("com.typesafe.sbt" % "sbt-uglify" % "1.0.3")

Next, modify your project build.sbt file and enable sbt-web:

lazy val root = (project in file(".")).enablePlugins(SbtWeb)

Declare the uglify sbt-web plugin execution:

pipelineStages := Seq(uglify)

This will make the build to uglify your javascript assets when making a release package (using activator dist). If you want to test the uglify in you dev environment use this line instead:

pipelineStages in Assets := Seq(uglify)

Finally, you need to modify the way the javascript assets are loaded in the twirl templates. Instead of @routes.Assets.at("something.js"), now use @routes.Assets.versioned("something.js")

Upvotes: 1

Atif
Atif

Reputation: 942

One approach you can try is creating a custom Play Filter which uses a Java-based compressor for JavaScript. Here is an example of one that I found: https://github.com/yui/yuicompressor/blob/master/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java

Another way is using a template which passes the generated JS into the above class.

Upvotes: 1

Related Questions