Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract plugins from a build.gradle file?

To simplify my build, I want to extract custom plugins from "build.gradle" and put them into separate gradle files.

Here's the simplest example I can contrive.


1. Defining a plugin inside build.gradle (WORKS)

The following "build.gradle":

apply plugin: GreetingPlugin

class GreetingPlugin implements Plugin<Project> {

    void apply(Project project) {

        project.task('hello') << {
            println "Hello, World"
        }
    }
}

When you run:

gradle hello

Produces:

:hello
Hello, World

BUILD SUCCESSFUL


2. Extracting the plugin from build.gradle (DOESN'T WORK)

I want to move the plugin definition into another file "hello.gradle":

class GreetingPlugin implements Plugin<Project> {

    void apply(Project project) {

        project.task('hello') << {
            println "Hello, World"
        }
    }
}

And change the "build.gradle" to be:

apply from: 'hello.gradle'
apply plugin: GreetingPlugin

Now when I run:

gradle hello

It produces:

FAILURE: Build failed with an exception.

* Where:
Build file 'build.gradle' line: 2

* What went wrong:
A problem occurred evaluating root project 'gradle-problem'.
> Could not find property 'GreetingPlugin' on root project 'gradle-problem'.

BUILD FAILED

Total time: 1.723 secs

I'm sure this must be possible, so how do you do it?

like image 901
ᴇʟᴇvᴀтᴇ Avatar asked Dec 03 '25 11:12

ᴇʟᴇvᴀтᴇ


1 Answers

I've found two reasonable solutions:

1. Apply the plugin inside the external file

hello.gradle:

apply plugin: GreetingPlugin

class GreetingPlugin implements Plugin<Project> {

    void apply(Project project) {

        project.task('hello').doLast {
            println "Hello, World"
        }
    }
}

build.gradle:

apply from: 'hello.gradle'


2. Export the plugin class by adding it to an ext property

hello.gradle:

class GreetingPlugin implements Plugin<Project> {

    void apply(Project project) {

        project.task('hello').doLast {
            println "Hello, World"
        }
    }
}

ext.GreetingPlugin = GreetingPlugin

build.gradle:

apply from: 'hello.gradle'
apply plugin: GreetingPlugin
like image 50
ᴇʟᴇvᴀтᴇ Avatar answered Dec 05 '25 10:12

ᴇʟᴇvᴀтᴇ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!