我正在开发一个Play 2.4应用程序,并希望SBT在编译期间运行webpack来生成静态资产。
我试过了https://github.com/stejskal/sbt-webpack,但它似乎对我不起作用。
答案 0 :(得分:31)
我设法通过定义一个自定义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
定义如下:
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
我希望这会有所帮助; - )
答案 1 :(得分:3)
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
答案 2 :(得分:1)
我们构建了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