0

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)
  }

}
pietro909
  • 1,811
  • 1
  • 19
  • 26

1 Answers1

0

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.

Jacob Wang
  • 4,411
  • 5
  • 29
  • 43
  • I didn't expect it to be that complex. I thought they were all bundled together by the framework :( – pietro909 Feb 13 '17 at 14:24
  • In this case it's good to decouple the React library itself from scalajs-react. But yeah there are some rough edges with scala.js - personally I just put the dependency in index.html directly. Things are gradually improving such as [being able to use commonJS modules](https://www.scala-js.org/news/2016/10/17/announcing-scalajs-0.6.13/) – Jacob Wang Feb 14 '17 at 00:49