How can you make a client-side javascript pages with scala.js and sbt's ScalaJSBundler?

389 views Asked by At

I'm using scala.js to create javascript code to be run in a browser, served up by an akka-http server. I had it mostly working using mill as my build tool, but then wanted to switch to sbt so I could use the ScalaJSBundler plugin for npm dependencies and packaging. Using sbt, when I do a fastOpt to compile my scala.js code, javascript code is created slightly different than what mill created and it now includes require statements (which the mill build didn't) such as

var $i_react = require("react");

When this code is run in my browser require comes up as undefined. Also variables I have exported in scala.js come up as undefined. I thought this was because the code being created was for ModuleKind.CommonJSModule (set via the sbt setting scalaJSModuleKind), but when I try to change that to ModuleKind.ESModule the build fails with:

scalaJSModuleKind must be set to ModuleKind.CommonJSModule in projects where ScalaJSBundler plugin is enabled

I'm new to javascript (and scala.js). What am I doing wrong? How should this be done?

Thank you!

1

There are 1 answers

1
sjrd On BEST ANSWER

As described in the Getting Started of scalajs-bundler, you should serve the result of webpack/fastOptJS to the browser, instead of fastOptJS. This is necessary because the latter is emitted as a CommonJS module, unsuitable for the browser, but then processed by Webpack to produce the former, a bundle suited for the browser, also containing the npm dependencies.