如何从SBT运行webpack

时间:2016-01-02 16:26:09

标签: playframework sbt webpack

我正在开发一个Play 2.4应用程序,并希望SBT在编译期间运行webpack来生成静态资产。

我试过了https://github.com/stejskal/sbt-webpack,但它似乎对我不起作用。

3 个答案:

答案 0 :(得分:31)

我设法通过定义一个自定义sbt任务来使其工作,该任务用于打包应用程序时调用的diststage任务。

任务的代码很简单:

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 runsbt stage一样工作。

GIVE.asia,我们正在使用它将VueAxiosVue-i18打包到一个JS文件中,该文件随后包含在我们的HTML文件中。然后,我们使用expose-loader公开变量VueVueI18naxios

首选sbt-webpack的原因是它会将输出文件生成到Playframework路由可以使用的适当位置。因为它与带有Playframework静态资产的增量编译集成。

这是仓库:https://github.com/GIVESocialMovement/sbt-webpack

或者您可以直接跳到一个有效的示例:https://github.com/GIVESocialMovement/sbt-webpack/tree/master/test-play-project