scalasbtscala.jsscalajs-bundlersbt-crossproject

Can the sbt-crossproject plugin support two Scala.js builds with two separate main classes, both with output managed by the scalajs-bundler plugin?


Suppose that you have a Scala.js project that compiles meaningfully to browser JavaScript, Node.js, and JVM.

Now imagine that in the browser, part of the application runs in the window while another part runs in a web worker.

Can SBT bundle two versions of the source code? One version has a main class for the browser window, while the other has a different main class that runs the web worker code?

If so, how would you configure this?

Please note that the project depends on JavaScript native libraries and webpack.


Solution

  • I'm doing exactly that in one of my projects, but with a main-class only for the JVM. The browser loads the transpiled scalajs-code and a small hook method, triggered by a js-file, initializing the core, with different parameters. This does work for Webworker and Frontend-thread and even for a SharedWorker

    This could look like that:

    importScripts("client-fullopt.js");
    importScripts("conf/app-config.js");
    
    MyProject.WebWorkerActorParent.initBackend(myProjectConfig);
    MyProject.WebWorkerActorParent.addWorker(this);
    

    at the frontend it could be a global script import and another initialization routine.

    <script src='client-fullopt.js' />
    <script>
      MyProject.WebWorkerActorParent.initFrontend();
    </script>
    

    Of course, nothing prevents you to additionally create different subprojects in sbt, that all use the same, common library-project and bundle their specific needs for the target platform in a separate project.