You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KAPT(Kotlin Annotation Processing)是否支持Kotlin-JS?有无示例?

KAPT Support for Kotlin/JS & Alternative Solution

Hey there! Let's get straight to the point: KAPT does NOT support Kotlin/JS.

KAPT was built specifically to integrate with the Java annotation processing ecosystem, which is deeply tied to the JVM platform. Since Kotlin/JS compiles directly to JavaScript (not JVM bytecode), the underlying mechanisms KAPT relies on simply don't apply here.

The Cross-Platform Alternative: KSP

The good news is JetBrains offers a modern, cross-platform replacement called KSP (Kotlin Symbol Processing) that fully supports Kotlin/JS (along with JVM and Native). KSP is designed from the ground up to handle annotation processing across all Kotlin targets, making it the ideal choice for JS-only or multi-platform projects.

Quick KSP Example for Kotlin/JS

Here's a simplified walkthrough to get you started:

1. Configure Your Build File (build.gradle.kts)

Add the KSP plugin and dependencies to your Kotlin/JS project:

plugins {
    kotlin("js") version "1.9.20"
    id("com.google.devtools.ksp") version "1.9.20-1.0.13"
}

repositories {
    mavenCentral()
}

kotlin {
    js(IR) {
        browser()
        binaries.executable()
    }
}

dependencies {
    // Annotation module (separate or inline)
    implementation(project(":annotations"))
    // KSP processor module
    ksp(project(":processor"))
}

2. Define a Custom Annotation

Create a simple annotation (you can put this in a shared module or directly in your project):

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class GenerateGreeting

3. Write the KSP Processor

Create a processor that generates code based on the annotation:

import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*

class GreetingProcessor : SymbolProcessor {
    override fun process(resolver: Resolver): List<KSAnnotated> {
        // Find all classes annotated with @GenerateGreeting
        resolver.getSymbolsWithAnnotation("com.yourpackage.GenerateGreeting")
            .filterIsInstance<KSClassDeclaration>()
            .forEach { classDecl ->
                val packageName = classDecl.packageName.asString()
                val className = classDecl.simpleName.asString()
                val generatedFile = "${className}Greeting.kt"
                
                // Generate a simple extension function
                val code = """
                    package $packageName
                    
                    fun $className.greet(): String = "Hello, I'm $className from Kotlin/JS!"
                """.trimIndent()
                
                // Write the generated code to a new file
                resolver.codeGenerator.createNewFile(
                    Dependencies(false),
                    packageName,
                    generatedFile
                ).write(code.toByteArray())
            }
        return emptyList()
    }

    // Register the processor with KSP
    companion object Provider : SymbolProcessorProvider {
        override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
            return GreetingProcessor()
        }
    }
}

Don't forget to register the processor by adding a file at resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider with the full class path of your provider (e.g., com.yourpackage.GreetingProcessor$Provider).

4. Use the Annotation in Your JS Code

Apply the annotation and use the generated code:

@GenerateGreeting
class MyJsComponent

fun main() {
    val component = MyJsComponent()
    println(component.greet()) // Outputs: Hello, I'm MyJsComponent from Kotlin/JS!
}

When you build your project, KSP will automatically generate the extension function file, and the code will run smoothly in your Kotlin/JS environment.

内容的提问来源于stack exchange,提问作者Freewind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:30:22