sbtscala.jsscalajs-react

ScalaJS with React: can't find React at runtime


I want to bootstrap a simple project with ScalaJS and React. It builds with fastOptJS, then I open my index.html with Chrome and I get this error at runtime:

enter image description here

Apparently, React's runtime is not available in the browser. In the documentation it doesn't mention any separate import of React, just the configuration of build.sbt.

I really can't understand what I'm doing wrong.

This is my index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>The Scala.js Tutorial</title>
  </head>
  <body>
    <!-- Include Scala.js compiled code -->
    <script type="text/javascript" src="./target/scala-2.12/hello-fastopt.js"></script>
    <!-- Run tutorial.webapp.TutorialApp -->
    <script type="text/javascript">
      web.TutorialApp().main();
    </script>
  </body>
</html>

This is my TutorialApp.scala

package web

import japgolly.scalajs.react._
import org.scalajs.dom
import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import japgolly.scalajs.react.ReactComponentB
import japgolly.scalajs.react.vdom.prefix_<^._

object TutorialApp extends JSApp {

  @JSExport
  def main(): Unit = {
    println("Hello world!")

    val App =
      ReactComponentB[Unit]("App")
        .render(_ => <.div("Hello!"))
        .build

    ReactDOM.render(App(), dom.document.body)
  }

}

Solution

  • You either need it globally (via <script> tags in index.html) or using webjars.

    If you want to use webjars/jsDependencies you can look at https://github.com/tastejs/todomvc/blob/gh-pages/examples/scalajs-react/build.sbt:

    jsDependencies ++= Seq(
      "org.webjars.bower" % "react" % "15.2.1" / "react-with-addons.js" minified "react-with-addons.min.js" commonJSName "React",
      "org.webjars.bower" % "react" % "15.2.1" / "react-dom.js"         minified "react-dom.min.js" dependsOn "react-with-addons.js" commonJSName "ReactDOM"
    )
    

    Also note that in their index.html they have added

    <script src="generated/todomvc-jsdeps.js"></script>

    to make sure the JS dependencies are loaded on the page too. You'll need to change the name of *-jsdeps.js depending on your project name.