-Ywarn-unused-import触发播放路由文件

我希望能够使用-Xfatal-warnings-Ywarn-unused-import ,问题是编译器在包含我的应用程序的播放path的文件上触发错误:

 [error] /path/to/app/conf/routes: Unused import [error] /path/to/app/conf/routes: Unused import [error] /path/to/app/conf/routes:1: Unused import [error] GET /document/:id my.app.controllers.MyController.getById(id: Int) 

其他路线也一样。

是否有可能告诉scalac忽略文件?

斯卡拉版本是2.11.8

一个可怕的“解决scheme”可能是在生成路由之后但运行编译任务之前删除那些未使用的导入。 这是一个草图:

 lazy val optimizeRoutesImports = taskKey[Unit]("Remove unused imports from generated routes sources.") optimizeRoutesImports := { def removeUnusedImports(targetFiles: (File) => PathFinder, linesToRemove: Set[String], linesToReplace: Map[String, String]) = { val files = targetFiles(crossTarget.value).get files foreach { file => val lines = sbt.IO.readLines(file) val updatedLines = lines map { line => linesToReplace.getOrElse(line, line) } filterNot { line => linesToRemove.contains(line.trim) } sbt.IO.writeLines(file, updatedLines, append = false) } } removeUnusedImports( _ / "routes" / "main" / "controllers" / "ReverseRoutes.scala", Set("import ReverseRouteContext.empty"), Map( "import play.api.mvc.{ QueryStringBindable, PathBindable, Call, JavascriptLiteral }" -> "import play.api.mvc.{ QueryStringBindable, PathBindable, Call }", "import play.core.routing.{ HandlerDef, ReverseRouteContext, queryString, dynamicString }" -> "import play.core.routing.{ ReverseRouteContext, queryString, dynamicString }" ) ) removeUnusedImports( _ / "routes" / "main" / "controllers" / "javascript" / "JavaScriptReverseRoutes.scala", Set( "import play.core.routing.{ HandlerDef, ReverseRouteContext, queryString, dynamicString }", "import ReverseRouteContext.empty" ), Map( "import play.api.mvc.{ QueryStringBindable, PathBindable, Call, JavascriptLiteral }" -> "import play.api.mvc.{ QueryStringBindable, PathBindable }" ) ) removeUnusedImports( _ / "routes" / "main" / "router" / "Routes.scala", Set("import play.core.j._"), Map()) } 

然后,您将需要清理任务依赖关系:

 // Our optimize routes imports task depends on the routes task. optimizeRoutesImports := (optimizeRoutesImports dependsOn (play.sbt.routes.RoutesKeys.routes in Compile)).value // And compilation depends on the unused routes having been removed. compile := ((compile in Compile) dependsOn optimizeRoutesImports).value 

在启用-Ywarn-unused-import之前,您还可能需要将TwirlKeys.templateImports设置为保守列表。 就像这样,取决于你的视图中使用的types:

 TwirlKeys.templateImports := Seq("play.api.mvc._", "play.api.i18n.Messages", "controllers.routes") 

我也不得不敲歪歪模板(YMMV)的未使用TemplateMagic导入:

  removeUnusedImports( _ / "twirl" ** "*.template.scala", Set("import play.twirl.api.TemplateMagic._"), Map()) 

如果这样做,请确保任务依赖性设置得当。

这对我有用。 斯卡拉2.11.8,播放2.5.10,两个 – -Xfatal-warnings-Ywarn-unused-import启用。 这是可怕的,但它的工作。