ChatGPT解决这个技术问题 Extra ChatGPT

What is the difference between allprojects and subprojects

On a multi-project gradle build, can someone tell me what exactly is the difference between the "allprojects" section and the "subprojects" one? Just the parent directory? Does anyone use both? If so, do you have general rules that determines what typically is put in each one?

Related question: what is the difference between the two syntaxes (really for allprojects AND subprojects):

subprojects {  ...
}

and

configure(subprojects) { ...
}

When would you one over the other?


J
Justin Ryan

In a multi-project gradle build, you have a rootProject and the subprojects. The combination of both is allprojects. The rootProject is where the build is starting from. A common pattern is a rootProject has no code and the subprojects are java projects. In which case, you apply the java plugin to only the subprojects:

subprojects {
    apply plugin: 'java'
} 

This would be equivalent to a maven aggregate pom project that just builds the sub-modules.

Concerning the two syntaxes, they do the exact same thing. The first one just looks better.


I'm trying to understand your answer, and why one would want "rootProject has no code"?
It can have code but most of the time it is just for combining all sub projects under a single root project.
P
Peter Niederwieser

Adding to Ryan's answer, the configure method becomes important when you want to configure custom subsets of objects. For example configure([project(":foo"), project(":bar")]) { ... } or configure(tasks.matching { it.name.contains("foo") }) { ... }.

When to use allprojects vs. subprojects depends on the circumstances. Often you'll use both. For example, code related plugins like the Java plugin are typically applied to subprojects, because in many builds the root project doesn't contain any code. The Eclipse and IDEA plugins, on the other hand, are typically applied to allprojects. If in doubt, look at examples and other builds and/or experiment. The general goal is to avoid irrelevant configuration. In that sense, subprojects is better than allprojects as long as it gives the expected results.


what if some of my sub projects depends on protocol buffers? should I apply proto-gradle-plugin across all ? or sub or only to those few projects in sub?
@user1870400 If i understand the answer correctly you should be able to use configure with a matching pattern to filter those subprojects that need a specific plugin.