Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating Play Framework and Twirl Templates with Webpack and React

I am currently migrating a Play Framework application with a view composed entirely of Twirl templates into one with a view composed of a mix of Twirl and React. I have written a PlayRunHook to integrate Webpack with Play's build process, and the result is JavaScript bundles whose names match what I have hardcoded in the new barebones Twirl templates.

So things look like this:

@(title: String)(implicit session: Session, staticAssetResolver: StaticAssetResolver)
@main(title) {
        <input type="hidden" name="pageTitle" id="pageTitle" value="@title">

        <div id="content">
        </div>

        <script language="JavaScript" src="@staticAssetResolver.asset("dist/profile.bundle.js")"></script>
}

The React code in the bundle knows to mount at the "content" div and receives props provided in the template.

This all works well, but I would like to avoid hardcoding the bundle name so that I can benefit from asset fingerprinting. This means figuring out a way to more tightly couple Webpack with Play's build process so that Webpack's output can be incorporated into the Twirl templates.

I have researched plugins, but what would you suggest for integrating Webpack and Twirl in this way?

like image 742
Vidya Avatar asked Sep 20 '25 22:09

Vidya


1 Answers

This is probably not what you want to hear - I too messed around with trying to figure out how to embed interactivity in Twirl... but in the ended I concluded it was a back idea to mix javascript and twirl, ended up doing this;

https://blog.usejournal.com/react-with-play-framework-2-6-x-a6e15c0b7bd

It could be that I'm simply not familiar enough with Twirl, but after wrestling for quite a while, I found that simply "changing worlds" into react, and having it talk to the backend via

fetch(/api/myRoute)

was quite productive. In conjunction with React Router I found myself very happy with the productivity, performance and outcome. I spent little time on "custom" build work, outside of copy and paste from that blog, so was able to concentrate on what I wanted.

I would also say that I am not skilful enough, and did not have time to start writing custom "RunHooks"... so that may also be the problem!

The above link worked well for me... with the only downside being that when changing routes one gets no tool support... so it is manual and risky to change a backend route or method signature. Probably not great for a big app... but for my small set of requirements was an effective strategy.

like image 90
Simon Avatar answered Sep 22 '25 11:09

Simon