scalaks-bootstrap: Uncaught ReferenceError: exports is not defined at scalajsenv.js:29

scalaks-bootstrap: Uncaught ReferenceError: exports is not defined at scalajsenv.js:29

我试着做一个简单的 scalajs + scalajs-bootstrap 应用程序,但是关于如何做的文档很少设置骨架。 scalajs-bootstrap 项目有一个示例,但是 build.sbt 文件非常大,它包含 scalajs-bootstrap 的源代码和示例本身。

我尝试仅使用 bootstrap4 示例创建一个新项目,但是当我在浏览器上打开 index.html 页面时,它会提示

Uncaught ReferenceError: exports is not defined at scalajsenv.js:29

这是我当前的设置:

project/plugins.sbt

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.20")
addSbtPlugin("com.github.karasiq" % "sbt-scalajs-bundler" % "1.2.1")
addSbtPlugin("ch.epfl.scala" % "sbt-scalajs-bundler" % "0.13.0")

build.sbt

enablePlugins(ScalaJSBundlerPlugin)

scalaVersion := "2.12.6"
libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.9.7"
libraryDependencies += "com.github.karasiq" %%% "scalajs-bootstrap-v4" % "2.3.5"

npmDependencies in Compile += "jquery" -> "3.2.1"
npmDependencies in Compile += "bootstrap" -> "4.1.1"

mainClass in Compile := Some("com.karasiq.bootstrap4.test.frontend.BootstrapTestApp")
scalaJSUseMainModuleInitializer := true

scalaJSModuleKind := ModuleKind.CommonJSModule
version in webpack := "4.28.4"
emitSourceMaps := false

这是scalajs-bootstrap4库的源代码和例子: https://github.com/Karasiq/scalajs-bootstrap

这是我完整的最小示例,它因 exports is not defined 错误而失败: https://github.com/dportabella/scalajs-bootstrap4-examples

如何修改 plugins.sbt and/or build.sbt 以使该项目正常运行?


解决方案

project/plugins.sbt

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.28")
addSbtPlugin("ch.epfl.scala" % "sbt-scalajs-bundler" % "0.13.0")

build.sbt

enablePlugins(ScalaJSBundlerPlugin)

scalaVersion := "2.12.8"
libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.9.7"
libraryDependencies += "com.github.karasiq" %%% "scalajs-bootstrap-v4" % "2.3.5"

npmDependencies in Compile += "jquery" -> "3.2.1"
npmDependencies in Compile += "bootstrap" -> "4.1.1"

mainClass in Compile := Some("com.karasiq.bootstrap4.test.frontend.BootstrapTestApp")
scalaJSUseMainModuleInitializer := true

scalaJSModuleKind := ModuleKind.CommonJSModule
version in webpack := "4.28.4"
emitSourceMaps := false

完整示例: https://github.com/dportabella/scalajs-bootstrap4-examples

根据我的经验,您需要:

  • 将以下行添加到您的 project/plugins.sbt:
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.25")
addSbtPlugin("ch.epfl.scala" % "sbt-scalajs-bundler" % "0.13.1")
  • build.sbt
  • 中同时启用 ScalaJSPluginScalaJSBundlerPlugin
  • 将以下配置添加到您的 build.sbt:
scalaJSUseMainModuleInitializer := true
scalaJSModuleKind := ModuleKind.CommonJSModule
version in webpack := "4.28.4"
emitSourceMaps := false

最后,运行fastOptJS::webpack创建打包的JS文件。

注意index.html中需要引用打包后的JS文件,而不是编译后的JS文件!

希望对您有所帮助。

像我一样使用sbt-web-scalajs的人请看:
https://scalacenter.github.io/scalajs-bundler/getting-started.html#sbt-web