【问题标题】:ScalaJS with React: can't find React at runtime带有 React 的 ScalaJS:在运行时找不到 React
【发布时间】:2017-02-13 11:06:50
【问题描述】:

我想用 ScalaJSReact 引导一个简单的项目。 它使用fastOptJS 构建,然后我用Chrome 打开我的index.html,运行时出现此错误:

显然,React 的运行时在浏览器中不可用。在documentation 中没有提到任何单独的React 导入,只是build.sbt 的配置。

我真的不明白我做错了什么。

这是我的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>

这是我的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)
  }

}

【问题讨论】:

    标签: sbt scala.js scalajs-react


    【解决方案1】:

    您要么全局需要它(通过index.html 中的&lt;script&gt; 标签),要么使用webjars。

    如果你想使用 webjars/jsDependencies 你可以查看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"
    )
    

    还要注意他们在index.html 中添加了

    &lt;script src="generated/todomvc-jsdeps.js"&gt;&lt;/script&gt;

    确保页面上也加载了 JS 依赖项。您需要根据您的项目名称更改*-jsdeps.js 的名称。

    【讨论】:

    • 没想到会这么复杂。我以为它们都被框架捆绑在一起了:(
    • 在这种情况下,最好将 React 库本身与 scalajs-react 分离。但是,是的,scala.js 有一些粗糙的边缘——我个人只是将依赖项直接放在 index.html 中。事情逐渐好转如being able to use commonJS modules
    猜你喜欢
    • 2017-06-02
    • 2016-01-12
    • 2017-06-12
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多