2

I have a localization resource file I need access from scala.js. It needs to be local to the script execution environment (i.e., not loaded asynchronously from a server, as recommended at How to read a resource file in Scala.js?).

Is there any mechanism for embedding the contents of a small resource file directly into the generated javascript compiled from a scala.js file? Basically, I want something like:

object MyResource {
    @EmbeddedResource(URL("/my/package/localized.txt"))
    val resourceString: String = ???
}

This would obviously bloat the generated .js file somewhat, but that is an acceptable tradeoff for my application. It seems like this wouldn't be an uncommon need and that this macro ought to already exist somewhere, but my initial searches haven't turned anything up.

1
  • AFAIK there's no mechanism like you're describing. Honestly, I'd probably just code that as a source-code file at that point... Commented Nov 18, 2017 at 16:40

1 Answer 1

3

If you are using sbt, you can use a source generator that reads your resource file and serializes it in a val inside an object:

sourceGenerators in Compile += Def.task {
  val baseDir = baseDirectory.value / "custom-resources" // or whatever
  val resourceFile = baseDir / "my/package/localized.txt"

  val sourceDir = (sourceManaged in Compile).value
  val sourceFile = sourceDir / "Localized.scala"

  if (!sourceFile.exists() ||
      sourceFile.lastModified() < resourceFile.lastModified()) {
    val content = IO.read(resourceFile).replaceAllLiterally("$", "$$")

    val scalaCode =
      s"""
      package my.package.localized

      object Localized {
        final val content = raw\"\"\"$content\"\"\"
      }
      """

    IO.write(sourceFile, scalaCode)
  }

  Seq(sourceFile)
}.taskValue

If you are using another build tool, I am sure there is a similar concept of source generators that you can use.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.