kotlingradlekotlin-js

How do you add css to a Kotlin JS project?


I created a new Kotlin/JS Gradle project using the wizard in IntelliJ.

I'm unclear how I'm supposed to add css to the project. The documentation explains how to enable css webpack support, but it doesn't actually say how to add the css file into your project (i.e., how to use the file).

For example, in a normal project, you would just import it in a javascript file. Since I am writing in Kotlin, how do I do it now?


Solution

  • The current documentation is not very precise about this. There are actually two cases:

    Importing CSS from existing packages

    You can pretty easily import CSS files from other Node-modules using the require() function:

    import kotlinext.js.require
    import kotlinx.browser.document
    import react.dom.h1
    import react.dom.render
    
    fun main() {
        require("bootstrap/dist/css/bootstrap.css")
        render(document.getElementById("root")) {
            h1 { +"Hello"}
        }
    }
    

    For this to work, you need to specify cssSupport.enabled = true in your Gradle build, just like described in the documentation. CSS imported this way will be processed by Webpack.

    Incorporating your own CSS into the Webpack build

    This seems to be a bit tricky right now. The KotlinJS plugin doesn't copy any resources to the Webpack's build directory (build/js/packages/<project_name>) by default and I didn't find any obvious configuration option for this. To solve it, you have to tell Webpack where it can find your styles:

    Create webpack.conf.d directory in project's root and put inside some JS file containing:

    config.resolve.modules.push("<your_stylesheet_dir>");

    This config will be picked up by the KotlinJS plugin and merged into the generated build/js/packages/<project_name>/webpack.config.js. With this configuration you can just require() project's styles like in the example above. It is kind of mentioned in the documentation.

    Alternatively you can tweak the Gradle build, so it copies the stylesheets into the Webpack's build dir:

    task("copyStylesheets", Copy::class) {
        from(kotlin.sourceSets["main"].resources) {
            include("styles/**")
        }
        into("${rootProject.buildDir}/js/packages/${kotlin.js().moduleName}")
        // kotlin { js { moduleName = "xyz" }} has to be set for this to work 
    }
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinJsDce::class) {
        dependsOn("copyStylesheets")
    }