Gradle is a fast, dependable, and adaptable open-source build automation tool with an elegant and extensible declarative build language. Gradle supports Android, Java, Kotlin Multiplatform, Groovy, Scala, JavaScript, and C/C++.
The Nx plugin for Gradle registers Gradle projects in your Nx workspace. It allows Gradle tasks to be run through Nx. Nx effortlessly makes your CI faster.
Nx adds the following features to your workspace:
- Cache task results
- Distribute task execution
- Run only tasks affected by a PR
- Interactively explore your workspace
Setup @nx/gradle
Section titled “Setup @nx/gradle”Install Nx
Section titled “Install Nx”You can install Nx globally. Depending on your package manager, use one of the following commands:
npm add --global nx@latestbrew install nxchoco install nxsudo add-apt-repository ppa:nrwl/nxsudo apt updatesudo apt install nxAdd Nx to a Gradle Workspace
Section titled “Add Nx to a Gradle Workspace”In any Gradle workspace, run the following command to add Nx and the @nx/gradle plugin:
nx initThen, you can run Gradle tasks using Nx. For example:
nx build <your gradle library>How @nx/gradle Infers Tasks
Section titled “How @nx/gradle Infers Tasks”The @nx/gradle plugin relies on a companion Gradle plugin, dev.nx.gradle.project-graph, to analyze your Gradle build structure. When using nx add, the Gradle plugin is added as a dependency to the root Gradle build file. In most cases, the generator will add the task definition to trigger the plugin, but if it's missing, add the following to your Gradle build file:
plugins { id("dev.nx.gradle.project-graph") version("+")}
allprojects { apply { plugin("dev.nx.gradle.project-graph") }}plugins { id 'dev.nx.gradle.project-graph' version '+'}
allprojects { apply plugin: 'dev.nx.gradle.project-graph'}The dev.nx.gradle.project-graph plugin introduces a task named nxProjectGraph. This task analyzes your Gradle projects and their tasks, outputting the structure as JSON. The @nx/gradle plugin then uses this JSON data to accurately build the Nx project graph. If Nx has any issues generating the project graph JSON, you can run the nxProjectGraph task manually:
./gradlew nxProjectGraph.\gradlew.bat nxProjectGraphVersion Compatibility
Section titled “Version Compatibility”The @nx/gradle Nx plugin requires a compatible version of the dev.nx.gradle.project-graph Gradle plugin. When you run nx migrate, the correct version is automatically updated in your Gradle build files. If you need to manually verify or set the version, use the following compatibility table.
| dev.nx.gradle.project-graph version | Minimum required @nx/gradle version | Breaking Change |
|---|---|---|
| 0.1.11 | 22.4+ | Added includeDependsOn field to executor options |
| 0.1.10 | 22.2 | Added nxConfig field to project node for Nx DSL support |
| 0.1.4 | 21.4 | Added excludeDependsOn field to executor options |
View Inferred Tasks
Section titled “View Inferred Tasks”To view inferred tasks for a project, open the project details view in Nx Console or run nx show project my-project in the command line.
Setting Up @nx/gradle in an Nx Workspace
Section titled “Setting Up @nx/gradle in an Nx Workspace”In any Nx workspace, you can install @nx/gradle by running the following command:
nx add @nx/gradle@nx/gradle Configuration
Section titled “@nx/gradle Configuration”The @nx/gradle plugin is configured in the plugins array in nx.json.
{ "plugins": [ { "plugin": "@nx/gradle", "options": { "testTargetName": "test", "ciTestTargetName": "test-ci", "targetNamePrefix": "gradle-", "gradleExecutableDirectory": "./gradle-projects" } } ]}Target Name Prefix
Section titled “Target Name Prefix”In a polyglot workspace supporting projects in different languages, you may have targets with the same name (e.g., build, test) but different behaviors. By default, Gradle task names are used directly as Nx target names. Use the targetNamePrefix option to prefix all Gradle targets with a custom string to distinguish them from other targets in your workspace.
For example, with "targetNamePrefix": "gradle-", Nx will recognize your targets as gradle-build, gradle-test, gradle-check, etc.
Test Target Name
Section titled “Test Target Name”The testTargetName option controls the name of the inferred test target. The default name is test.
Custom Gradle Executable Directory
Section titled “Custom Gradle Executable Directory”By default, the @nx/gradle plugin executes the Gradle wrapper found in your project root. If no wrapper exists there, it searches up through parent directories to the workspace root. To use a Gradle wrapper from a custom location, specify the directory path in your nx.json under the plugins array using the gradleExecutableDirectory option.
Batch Mode
Section titled “Batch Mode”Batch mode allows Nx to send multiple Gradle tasks to Gradle in a single invocation rather than running each task separately. This significantly reduces the overhead of starting multiple Gradle processes and allows Gradle to optimize task execution internally.
Set the NX_BATCH_MODE environment variable to true:
NX_BATCH_MODE=true nx run-many -t build testTest Distribution
Section titled “Test Distribution”Nx provides powerful features for distributing tasks in CI, including test splitting (also known as atomization) and optimized build targets. For Gradle projects, this is facilitated by the @nx/gradle plugin, allowing you to run your tests and builds more efficiently in your Continuous Integration (CI) environment.
How to Set Up Test Distribution (Atomizer) in CI
Section titled “How to Set Up Test Distribution (Atomizer) in CI”To enable test distribution for your Gradle projects in CI, follow these steps:
Generate CI Workflow: Run the
ci-workflowgenerator to set up the necessary CI configurations. This generator creates a GitHub Actions workflow file that integrates with Nx's distributed task execution capabilities.Terminal window nx g @nx/gradle:ci-workflowThis command will generate a workflow file (e.g.,
.github/workflows/ci.yml) tailored for your Nx workspace with Gradle projects.Configure
nx.jsonfor Atomizer: Add or ensure the presence ofciTestTargetNamein the@nx/gradleplugin options within yournx.json.nx.json {"plugins": [{"plugin": "@nx/gradle","options": {"ciTestTargetName": "test-ci"}}]}Setting this option turns on the atomizer feature in CI. Nx will automatically split your testing tasks by test class, allowing them to be run in a distributed fashion across your CI agents.
Update CI Workflow Command: In your generated CI workflow file, modify the command used to run affected tasks. Instead of using a generic
buildtarget, leverage thebuild-citarget provided by the@nx/gradleplugin:Terminal window # Before:# ./nx affected --base=$NX_BASE --head=$NX_HEAD -t build# After:./nx affected --base=$NX_BASE --head=$NX_HEAD -t build-ciThis ensures that your CI pipeline utilizes the optimized
build-citarget, which is designed to integrate seamlessly with Nx's test distribution and caching mechanisms.
The ci-workflow Generator
Section titled “The ci-workflow Generator”The @nx/gradle:ci-workflow generator is a utility that automates the setup of a CI workflow for your Nx workspace containing Gradle projects. It creates a .github/workflows file (or equivalent for other CI providers) that includes steps for checking out code, setting up Java and Gradle, restoring caches, and running affected Nx tasks. Its primary purpose is to streamline the integration of Nx's CI features, such as distributed task execution and caching, into your existing CI pipeline.
The build-ci Target
Section titled “The build-ci Target”The @nx/gradle plugin can create a build-ci target that is specifically designed for use in CI environments. This target allows for a more optimized and consistent build process by ensuring that the check task is rewired to its CI counterpart (check-ci), which also implies that test tasks are rewired to their atomized test-ci counterparts.
What is it?
Section titled “What is it?”The build-ci target is a synthetic Nx target that acts as a placeholder for your Gradle build task in a CI context. Instead of directly running the build task, the build-ci target ensures that the check task (a dependency of build) first executes its CI-optimized version (check-ci), which in turn uses the split/atomized test tasks. This allows for distributed execution of tests and efficient caching in CI.
How to Enable?
Section titled “How to Enable?”To enable the build-ci target, you need to configure ciTestTargetName in the @nx/gradle plugin options in your nx.json.
For example:
{ "plugins": [ { "plugin": "@nx/gradle", "options": { "ciTestTargetName": "test-ci", "ciBuildTargetName": "build-ci" } } ]}When ciTestTargetName is set, the build-ci target is automatically created if the build task exists for a given Gradle project.
Expected Behavior
Section titled “Expected Behavior”When you run nx build-ci <your-gradle-project>, Nx will:
- Execute the
check-citask (if defined) instead of the standardchecktask. - The
check-citask will, in turn, trigger the atomized test tasks if they are configured. - The
build-citarget itself will use thenx:noopexecutor, meaning it doesn't execute a direct Gradle command, but rather relies on its dependencies (check-ci) to orchestrate the build process in a CI-friendly manner. - The
build-citarget is cacheable.
This setup ensures that your build process in CI leverages Nx's caching and distribution capabilities effectively.
Continuous Tasks
Section titled “Continuous Tasks”Gradle doesn't have a standard way to identify tasks which are continuous, like bootRun for serving a Spring Boot project. To ensure Nx handles these continuous tasks correctly, you can explicitly mark them as continuous.
In the nx.json, you can specify the target default configuration like so:
{ "targetDefaults": { "someTask": { "continuous": true } }}In a project.json, you can specify the target configuration like so:
{ "someTask": { "continuous": true }}Configuring Projects and Tasks with the Gradle DSL
Section titled “Configuring Projects and Tasks with the Gradle DSL”The dev.nx.gradle.project-graph plugin provides a type-safe nx {} DSL for configuring Nx-specific metadata on your Gradle projects and tasks. This allows you to customize project metadata, configure task dependencies, and control caching behavior directly in your Gradle build files.
Project-Level Configuration
Section titled “Project-Level Configuration”Use the nx {} block at the project level to configure Nx in any way you would in project.json:
import dev.nx.gradle.nx
nx { // Set project name set("name", "my-custom-project-name")
// Add tags for organization array("tags", "api", "backend", "tier:1")
// Add nested metadata set("metadata") { set("owner", "team-payments") set("criticality", "high") }}import static dev.nx.gradle.Groovy.nx
nx(project) { // Set project name it.set 'name', 'my-custom-project-name'
// Add tags for organization it.array 'tags', 'api', 'backend', 'tier:1'
// Add nested metadata it.set 'metadata', { it.set 'owner', 'team-payments' it.set 'criticality', 'high' }}Available DSL methods for project-level configuration:
set(key, value)- Set string, number, or boolean valuesarray(key, ...values)- Set array valuesset(key) { ... }- Create nested objectsmerge(map)- Merge a map of properties
Task-Level Configuration
Section titled “Task-Level Configuration”Use the nx {} block on individual Gradle tasks to configure target-specific behavior:
import dev.nx.gradle.nx
tasks { build { nx { // Configure caching set("cache", true)
// Add target tags array("tags", "integration", "slow")
// Add any custom configuration set("options") { set("timeout", 300) } } }}import static dev.nx.gradle.Groovy.nx
tasks.named('integrationTest') { nx(it) { // Configure caching it.set 'cache', true
// Add target tags it.array 'tags', 'integration', 'slow'
// Add any custom configuration it.set 'options', { it.set 'timeout', 300 } }}Available DSL methods for task-level configuration:
set(key, value)- Set string, number, or boolean valuesarray(key, ...values)- Set array valuesset(key) { ... }- Create nested objectsmerge(map)- Merge a map of properties