Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

gradle - 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?

question from:https://stackoverflow.com/questions/65876423/how-do-you-add-css-to-a-kotlin-js-project

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...