Embedding resources in scala.js

霸气de小男生 提交于 2020-02-25 06:33:45

问题


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:


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.



来源:https://stackoverflow.com/questions/47368250/embedding-resources-in-scala-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!