如何使用Webpack组织Kotlin SPA的前端和后端

时间:2018-05-09 18:47:20

标签: gradle webpack kotlin single-page-application

我正在后端开发一个带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中,以便后端提供服务?

是否有关于组织此类项目的建议?

2 个答案:

答案 0 :(得分:1)

答案 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的路线