适用于Android根项目的自定义Gradle插件

tf7tbtn2  于 2023-08-06  发布在  Android
关注(0)|答案(1)|浏览(100)

在我的示例Android应用程序中
根项目build.gradle包含

plugins {
    id 'com.android.application' version '7.2.2' apply false
    id 'com.android.library' version '7.2.2' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}

字符串
我正试图将其翻译为自定义gradle-plugin

class CustomGradlePlugin : Plugin<Project> {
    override fun apply(target: Project) {
        target.plugins.withId("com.android.application") {
            it.extraProperties.set("version",  "7.2.2")
            it.apply(false)
        }
        target.plugins.withId("com.android.library") {
            it.extraProperties.set("version",  "7.2.2")
            it.apply(false)
        }
        target.plugins.withId("org.jetbrains.kotlin.android") {
            it.extraProperties.set("version",  "1.7.10")
            it.apply(false)
        }
    }
}


当应用插件时,Gradle抛出:

> Failed to apply plugin
 > Configuration with name 'api' not found.


如何创建这个自定义gradle插件?
我尝试在应用另一个插件之前应用org.jetbrains.kotlin.android,但收到了相同的错误。

mzaanser

mzaanser1#

您是否已将插件添加到您的build.gradle文件?

build.gradle(来自BuilSrc或IncludedBuild)

gradlePlugin {
 plugins {
    create("custom gradle plugin") {
        id = "custom-gradle-plugin"
        implementationClass = "CustomGradlePlugin"
    }
 }

  //other blocks...
}

字符串

在yout root build.gradle中申请

plugins {
 id 'custom-gradle-plugin'
}

或者您也可以执行以下操作
build.gradle(来自BuilSrc或IncludedBuild)

plugins {
  `kotlin-dsl`
}

gradlePlugin {
  plugins {
    create("custom gradle plugin") {
        id = "custom-gradle-plugin"
        implementationClass = "CustomGradlePlugin"
    }
  }

  dependencies {
     implementation("com.android.tools.build:gradle:7.4.2")
     implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.22")
  }
}

自定义插件

class CustomGradlePlugin : Plugin<Project> {

  override fun apply(target: Project) {
     pluginManager.apply {
       apply("com.android.application")
       apply("com.android.library")
       apply("org.jetbrains.kotlin.android")
    }
  }
}

相关问题