简体   繁体   中英

Play Framework with React in Webjar

What I am looking for is a way to make the development with Play and React happens smoothly. I was hoping that if I use ReactJS in Webjar, there would be a way that I can use JSX transformer in development, and have the JSX compiled in production, ie when I run activator dist command. Is there a way to achieve such a development workflow?

Here is my build.sbt

name := "play-scala"

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.11.6"

libraryDependencies ++= Seq(
  "org.webjars" %% "webjars-play" % "2.3.0-2",
  "org.webjars.bower" % "react" % "0.13.1"
)

and here is a sample scala template react.scala.html

@main("React in Webjar") {

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

    <script src="@routes.Assets.at("lib/react/react.js")" type="text/javascript" ></script>
    <script src="@routes.Assets.at("lib/react/JSXTransformer.js")" type="text/javascript" ></script>
    <script src="@routes.Assets.at("javascripts/reactApp.jsx")" type="text/jsx"></script>
}

I am using a Bower Webjars. I wonder if that can help.

You will have to use a jsx compilation plugin that you can use to compile .jsx files into .js, for example this: https://github.com/ddispaltro/sbt-reactjs

You will then need to use different import blocks in your templates depending on if running as in dev or prod, something like this:

@if(play.api.Play.current.mode == play.api.Mode.Prod) {
  <script src="@routes.Assets.at("lib/react/react.js")" type="text/javascript" ></script>
  <script src="@routes.Assets.at("javascripts/reactApp.js")" type="text/jsx"></script>
} else {
  <script src="@routes.Assets.at("lib/react/react.js")" type="text/javascript" ></script>
  <script src="@routes.Assets.at("lib/react/JSXTransformer.js")" type="text/javascript" ></script>
  <script src="@routes.Assets.at("javascripts/reactApp.jsx")" type="text/jsx"></script>
}

More elaborate setups can be achieved using requirejs and other module managing schemes, but this is the simplest solution in a small project IMHO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM