首页 > 解决方案 > 使用 ScalaJSBundlerPlugin (webpack bundler) 时无法从 Javascript 访问 JSExport

问题描述

我正在尝试在此处找到的以下 scalajs 导出的 hello world 示例:

@JSExportTopLevel("HelloWorld")
object HelloWorld {
  @JSExport
  def sayHello(): Unit = {
    println("Hello world!")
  }
}

我的 html 看起来像这样:

<!DOCTYPE html>
<html>
<head>
  <title>Example Scala.js application</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body style="margin: 0px">

<script type="text/javascript" src="./../../../target/scala-2.13/scala-js-tutorial-fastopt.js"></script>
<script>
    HelloWorld.sayHello();
</script>
</body>
</html>

效果很好。

现在,如果我尝试使用 ScalaJSBundlerPlugin(它在后台使用 webpack),运行fastOptJS::webpack并将路径更改为“./../../../target/scala-2.13/scalajs-bundler/main/scala-js- tutorial-fastopt-bundle.js”,我得到“HelloWorld 未定义”。

捆绑后如何访问 HelloWorld?

标签: webpackscala.js

解决方案


默认情况下,scalajs-bundler 使用“应用程序”捆绑模式,可以丢弃顶级导出。正如食谱中解释的那样,使用时@JSExportTopLevel,您需要使用“LibraryAndApplication”捆绑模式,使用

webpackBundlingMode := BundlingMode.LibraryAndApplication()

推荐阅读