summaryrefslogtreecommitdiff
path: root/plugin/src/main/scala/scala/js/resource/Plugin.scala
blob: f7af5e73541637ef4ef8f6ea7c3c2d6121eed0d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package scala.js.resource

import sbt._
import Keys._
import scala.scalajs.sbtplugin.ScalaJSPlugin.ScalaJSKeys._
import org.apache.commons.codec.binary.Base64


object Plugin extends sbt.Plugin {

  val resourceSettings = Seq(
    watchSources := {
      watchSources.value ++ (resources in Compile).value
    },
    packageJS := {

      val fileData = for{
        resourceRoot <- (resources in Compile).value
        (file, path) <- Path.allSubpaths(resourceRoot)
      } yield {
        val b64 = Base64.encodeBase64String(IO.readBytes(file))
        path -> b64
      }

      val bundle = crossTarget.value / "resources.js"
      val fileLines = for((path, data) <- fileData) yield {
        "    \"" + path + "\": \"" + data + "\""
      }

      IO.write(bundle, "\nScalaJS.resources = {\n" + fileLines.mkString(",\n") + "\n}" )

      (packageJS in Compile).value :+ bundle
    }
  )
}