我正在后端开发一个带Kotlin(Ktor)的SPA。项目结构现在是:
.
├── frontend/ <-- SPA frontend source project
│ ├── dist/ <-- current webpack dist
│ ├── node_modules/ <-- not to be included in the jar
│ ├── src/ <-- to be bundled by webpack
│ │ └── index.js
│ ├── index.html <-- to be served as static by backend
│ ├── package.json <-- not to be included in the jar
│ └── webpack.config.json <-- not to be included in the jar
│
├── src/ <-- SPA backend source
| └── main/
| ├── kotlin/
| | └── Main.kt <-- backend entry point
| └── resources/ <-- framework-specific configuration
│
├── build.gradle
└── settings.gradle
前端使用cd frontend && npm run build
成功编译,将生成的包存储到frontend/dist
。
Ktor路由设置:
fun Application.main() {
install(DefaultHeaders)
install(CallLogging)
routing {
static("/") {
default("frontend/index.html") // to be replaced with index file
// from packaged frontend
}
// ... other dynamic routes for REST
}
}
build.gradle很标准:
buildscript {
ext.kotlin_version = '1.2.41'
ext.ktor_version = '0.9.2'
ext.koin_ktor_version = '0.9.2'
ext.ktor_gson_version = '0.9.2'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
group 'org.root_talis'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'MainKt'
kotlin { experimental { coroutines "enable" } }
repositories {
mavenCentral()
jcenter()
maven { url "https://dl.bintray.com/kotlin/ktor" }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
compile "io.ktor:ktor-server-netty:$ktor_version"
compile "io.ktor:ktor-gson:$ktor_gson_version"
compile "ch.qos.logback:logback-classic:1.2.1"
compile "org.koin:koin-ktor:$koin_ktor_version"
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
如何让Gradle通过npm run build
编译前端项目,并将dist
打包到生成的JAR中,以便后端提供服务?
是否有关于组织此类项目的建议?
答案 0 :(得分:1)
看看这个项目:https://github.com/yole/kxhtml-isomorphic 并阅读http://kotlinlang.org/docs/reference/multiplatform.html#multiplatform-projects
答案 1 :(得分:1)
如果您需要运行某些npm
命令,则可以在正在使用的计算机上安装Node,声明一个Exec
任务并使build
任务依赖于此。
val npmBuilder by tasks.creating(Exec::class){
// some stuff
}
tasks.getByName("build").dependsOn(npmBuilder)
看看Exec
任务here的文档。
否则,您可以应用this Node plugin for Gradle,以免依赖机器设置。
此外,我建议不要使用this Ktor Feature
处理您SPA的路线