如何从SBT运行webpack

问题描述 投票:16回答:3

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

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

playframework sbt webpack
3个回答
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)

Webpackdefined如下:

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

我希望这有帮助 ;-)


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

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

© www.soinside.com 2019 - 2024. All rights reserved.