我正在开发一个Play 2.4应用程序,并希望SBT在编译期间运行webpack来生成静态资产。
我试过https://github.com/stejskal/sbt-webpack但它似乎对我不起作用。
我设法通过定义一个自定义sbt任务来工作,该任务使用了在打包应用程序时调用的dist
和stage
任务的依赖关系。
任务的代码是直截了当的:
lazy val webpack = taskKey[Unit]("Run webpack when packaging the application")
def runWebpack(file: File) = {
Process("webpack", file) !
}
webpack := {
if(runWebpack(baseDirectory.value) != 0) throw new Exception("Something goes wrong when running webpack.")
}
dist <<= dist dependsOn webpack
stage <<= stage dependsOn webpack
在开发模式下,我使用play action hooks在代码更改时运行webpack watch
:
PlayKeys.playRunHooks <+= baseDirectory.map(Webpack.apply)
与Webpack
defined如下:
import java.net.InetSocketAddress
import play.sbt.PlayRunHook
import sbt._
object Webpack {
def apply(base: File): PlayRunHook = {
object WebpackHook extends PlayRunHook {
var process: Option[Process] = None
override def beforeStarted() = {
process = Option(
Process("webpack", base).run()
)
}
override def afterStarted(addr: InetSocketAddress) = {
process = Option(
Process("webpack --watch", base).run()
)
}
override def afterStopped() = {
process.foreach(_.destroy())
process = None
}
}
WebpackHook
}
}
它就像一个魅力。您可以在我的github帐户中找到使用此技术的示例游戏项目:https://github.com/nouhoum/play-react-webpack/blob/master/webpack.sbt
我希望这有帮助 ;-)
Nouhoum的答案工作正常,直到我更新到SBT 1.0.x.
只需要几个更新:
import scala.sys.process.Process
lazy val webpack = taskKey[Unit]("Run webpack when packaging the application")
def runWebpack(file: File) = {
Process("npm run build", file) !
}
webpack := {
if(runWebpack(baseDirectory.value) != 0) throw new Exception("Something went wrong when running webpack.")
}
dist := (dist dependsOn webpack).value
stage := (stage dependsOn webpack).value
我们已经构建了sbt-webpack
,它与Playframework的静态资产的渐进式编译完美地集成在一起。我希望你想要的。它与sbt run
和sbt stage
一样有效。
在GIVE.asia,我们使用它将Vue
,Axios
和Vue-i18
打包成一个JS文件,后来包含在我们的HTML文件中。然后,我们使用expose-loader
来暴露变量Vue
,VueI18n
和axios
。
更喜欢sbt-webpack
的原因是它将输出文件生成到Playframework路由可以使用的适当位置。因为它与Playframework的静态资产的增量编译集成在一起。
这是回购:https://github.com/GIVESocialMovement/sbt-webpack
或者你可以直接跳到一个有效的例子:https://github.com/GIVESocialMovement/sbt-webpack/tree/master/test-play-project