首页 > 解决方案 > Gradle:使用兄弟子项目作为插件

问题描述

我有一个包含两个子对象的项目:gradle-pluginplugin-consumer. 我想将插件应用gradle-pluginplugin-consumer. 我试图这样做:

// plugin-consumer/build.gradle

buildscript {
    dependencies {
        classpath project(':gradle-plugin')
    }
}

apply plugin: 'my.plugin.id'

但是我遇到了以下错误:

A problem occurred configuring project ':plugin-consumer'.
> Cannot use project dependencies in a script classpath definition.

我认为这不受支持,因为它需要完全构建gradle-plugin才能plugin-consumer配置。

幸运的是,我可以使用fileTree依赖项来实现我的目标:

// plugin-consumer/build.gradle

buildscript {
    dependencies {
        classpath fileTree(includes: ['*.jar'], dir: '../gradle-plugin/build/libs')
    }
}

apply plugin: 'my.plugin.id'

这行得通,但感觉就像一个大规模的黑客攻击并导致“引导问题”。

例如,我不能,clean gradle-plugin因为(已删除)jar 文件是配置所必需的plugin-consumer,而必须在(重新)构建时完成gradle-plugin。幸运的是,这可以通过总是build在之后立即运行来避免(可以说是clean在同一个“运行”中)。这可以手动(gradle clean build)或自动(使用clean.finalizedBy(build))完成。再次,这有效,但感觉就像一个黑客。

最后,我的实际问题是:有没有更好的方法来做到这一点?

请注意,这gradle-plugin是一个独立的插件,不仅由 使用plugin-consumer,因此buildSrc很遗憾在这里不是合适的解决方案。

标签: gradlegradle-plugin

解决方案


您可以使用Maven 发布插件将该插件发布到本地 Maven 存储库。然后像任何其他工件一样简单地使用它。

假设您的插件项目中有类似的东西:

plugins {
    `maven-publish`
    `java-gradle-plugin`
}

只需在本地发布它:

./gradlew :my-plugin-project:publishToMavenLocal

然后在您的消费项目中,例如:

buildscript {
    repositories {
        mavenLocal()
    }
    dependencies {
        "classpath"("com.example:my-plugin-gav:1.0.0-SNAPSHOT")
    }
}

// apply plugin

推荐阅读