Accessing scala.js output in resources

168 views Asked by At

I'm trying to build a application server using scala.js, scalatags, akka-http, and mill as my build tool. All goes well until the browser tries to find scripts with generated scala.js code. This is the scalatags code which successfully gets built and references the compiled scala.js code (HiPage.js - built as a ScalaJSModule in mill). When it is run the println below prints out: file:/Users/nnovod/projects/lims/LIMS/resources/HiPage.js which is indeed where I've placed the javascript output from scala.js

object HiPage {
  val boot =
    "Hi().main(document.getElementById('contents'))"
  println(getClass.getResource("/HiPage.js").toString) 
  val skeleton =
    html(
      head(
        script(`type`:="text/javascript", src:="/HiPage.js"),
        link(
          rel:="stylesheet",
          href:="https://cdnjs.cloudflare.com/ajax/libs/pure/0.5.0/pure-min.css"
        )
      ),
      body(
        onload:=boot,
        div(id:="contents")
      )
    )
}

This eventually shows up in the browser as follows:

<html>
<head>
    <script type="text/javascript" src="/HiPage.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/0.5.0/pure-min.css"/>
</head>
<body onload="Hi().main(document.getElementById('contents'))">
    <div id="contents"></div>
</body>
</html>

This is my akka-http route...

    val route =
      path("hello") {
        get {
          complete(
            HttpEntity(
              ContentTypes.`text/html(UTF-8)`,
              HiPage.skeleton.render
            )
          )
        }
      }

The browser can never find the HiPage.js ("Failed to load resource: the server responded with a status of 404 (Not Found)"). HiPage.js is in a top level resources directory and is found by the println(getClass.getResource("/HiPage.js").toString) in the code. What do I have to do to get it seen when the browser requests it from the server?

1

There are 1 answers

0
nnovod On BEST ANSWER

Not sure if this is the best way but I finally was able to solve the problem by having all src references in script start with /resource and then editing my akka-http route to include the following:

        pathPrefix("resource") {
          extractUnmatchedPath { unmatched =>
            val resource = unmatched.toString()
            if (!resource.startsWith("/"))
              reject()
            else
              getFromResource(resource.substring(1))
          }
        }