Building and Testing React Apps in Nx
In this tutorial, you'll learn how to create a new React monorepo using the Nx platform.
This tutorial requires a GitHub account to demonstrate the full value of Nx - including task running, caching, and CI integration.
What will you learn?
- how to create a new React workspace with GitHub Actions preconfigured
- how to run a single task (i.e. serve your app) or run multiple tasks in parallel
- how to modularize your codebase with local libraries for better code organization
- how to benefit from caching that works both locally and in CI
- how to set up self-healing CI to apply fixes directly from your local editor
Creating a new React Monorepo
To get started, let's create a new React monorepo with Nx Cloud and GitHub Actions preconfigured.
Create a new React monorepoWith Nx and GitHub Actions fully set up
You should now have a new workspace called acme
with Vite, Vitest, ESLint, and Prettier preconfigured.
1acme
2├── .github
3│ └── workflows
4│ └── ci.yml
5├── apps
6│ └── demo
7├── README.md
8├── eslint.config.mjs
9├── nx.json
10├── package-lock.json
11├── package.json
12├── tsconfig.base.json
13├── tsconfig.json
14└── vitest.workspace.ts
15
The .github/workflows/ci.yml
file preconfigures your CI in GitHub Actions to run build and test through Nx.
The demo
app is created under the apps
directory as a convention. Later in this tutorial we'll create libraries under the packages
folder. In practice, you can choose any folder structure you like.
The nx.json
file contains configuration settings for Nx itself and global default settings that individual projects inherit.
Before continuing, it is important to make sure that your GitHub repository is connected to your Nx Cloud organization to enable remote caching and self-healing in CI.
Checkpoint: Workspace Created and Connected
At this point you should have:
- A new Nx workspace on your local machine with a React app in
apps/demo
- A new GitHub repository for the workspace with
.github/workflows/ci.yml
pipeline preconfigured - A workspace in Nx Cloud that is connected to the GitHub repository
You should see your workspace in your Nx Cloud organization.
If you do not see your workspace in Nx Cloud then please follow the steps outlined in the Nx Cloud setup.
Now, let's build some features and see how Nx helps get us to production faster.
Serving the App
To serve your new React app, run:
❯
npx nx serve demo
The app is served at http://localhost:4200.
Nx uses the following syntax to run tasks:
Inferred Tasks
Nx identifies available tasks for your project from tooling configuration files such as package.json
scripts and vite.config.ts
. To view the tasks that Nx has detected, look in the Nx Console project detail view or run:
❯
npx nx show project demo
@acme/demo
Root: apps/demo
Type:application
Targets
build
vite build
Cacheable
If you expand the build
task, you can see that it was created by the @nx/vite
plugin by analyzing your vite.config.ts
file. Notice the outputs are defined as {projectRoot}/dist
. This value is being read from the build.outDir
defined in your vite.config.ts
file. Let's change that value in your vite.config.ts
file:
1export default defineConfig({
2 // ...
3 build: {
4 outDir: './build',
5 // ...
6 },
7});
8
Now if you look at the project details view, the outputs for the build target will say {projectRoot}/build
. The @nx/vite
plugin ensures that tasks and their options, such as outputs, are automatically and correctly configured.
You can override the options for inferred tasks by modifying the targetDefaults
in nx.json
or setting a value in your package.json
file. Nx will merge the values from the inferred tasks with the values you define in targetDefaults
and in your specific project's configuration.
Modularization with Local Libraries
When you develop your React application, usually all your logic sits in the app's src
folder. Ideally separated by various folder names which represent your domains or features. As your app grows, however, the app becomes more and more monolithic, which makes building and testing it harder and slower.
1acme
2├── apps
3│ └── demo
4│ └── src
5│ ├── app
6│ ├── cart
7│ ├── products
8│ ├── orders
9│ └── ui
10└── ...
11
Nx allows you to separate this logic into "local libraries." The main benefits include
- better separation of concerns
- better reusability
- more explicit private and public boundaries (APIs) between domains and features
- better scalability in CI by enabling independent test/lint/build commands for each library
- better scalability in your teams by allowing different teams to work on separate libraries
Create Local Libraries
Let's create a reusable design system library called ui
that we can use across our workspace. This library will contain reusable components such as buttons, inputs, and other UI elements.
1npx nx g @nx/react:library packages/ui --unitTestRunner=vitest --bundler=none
2
Note how we type out the full path in the directory
flag to place the library into a subfolder. You can choose whatever folder structure you like to organize your projects.
Running the above commands should lead to the following directory structure:
1acme
2├── apps
3│ └── demo
4├── packages
5│ └── ui
6├── eslint.config.mjs
7├── nx.json
8├── package-lock.json
9├── package.json
10├── tsconfig.base.json
11├── tsconfig.json
12└── vitest.workspace.ts
13
Just as with the demo
app, Nx automatically infers the tasks for the ui
library from its configuration files. You can view them by running:
❯
npx nx show project ui
In this case, we have the lint
and test
tasks available, among other inferred tasks.
❯
npx nx lint ui
❯
npx nx test ui
Import Libraries into the Demo App
All libraries that we generate are automatically included in the workspaces
defined in the root-level package.json
.
1{
2 "workspaces": ["apps/*", "packages/*"]
3}
4
Hence, we can easily import them into other libraries and our React application.
You can see that the AcmeUi
component is exported via the index.ts
file of our ui
library so that other projects in the repository can use it. This is our public API with the rest of the workspace and is enforced by the exports
field in the package.json
file. Only export what's necessary to be usable outside the library itself.
1export * from './lib/ui';
2
Let's add a simple Hero
component that we can use in our demo app.
1export function Hero(props: {
2 title: string;
3 subtitle: string;
4 cta: string;
5 onCtaClick?: () => void;
6}) {
7 return (
8 <div
9 style={{
10 backgroundColor: '#1a1a2e',
11 color: 'white',
12 padding: '100px 20px',
13 textAlign: 'center',
14 }}
15 >
16 <h1
17 style={{
18 fontSize: '48px',
19 marginBottom: '16px',
20 }}
21 >
22 {props.title}
23 </h1>
24 <p
25 style={{
26 fontSize: '20px',
27 marginBottom: '32px',
28 }}
29 >
30 {props.subtitle}
31 </p>
32 <button
33 onClick={props.onCtaClick}
34 style={{
35 backgroundColor: '#0066ff',
36 color: 'white',
37 border: 'none',
38 padding: '12px 24px',
39 fontSize: '18px',
40 borderRadius: '4px',
41 cursor: 'pointer',
42 }}
43 >
44 {props.cta}
45 </button>
46 </div>
47 );
48}
49
Then, export it from index.ts
.
1export * from './lib/hero';
2export * from './lib/ui';
3
We're ready to import it into our main application now.
1import { Route, Routes } from 'react-router-dom';
2// importing the component from the library
3import { Hero } from '@acme/ui';
4
5export function App() {
6 return (
7 <>
8 <h1>Home</h1>
9 <Hero
10 title="Welcmoe to our Demo"
11 subtitle="Build something amazing today"
12 cta="Get Started"
13 />
14 </>
15 );
16}
17
18export default App;
19
Serve your app again (npx nx serve demo
) and you should see the new Hero component from the ui
library rendered on the home page.
If you have keen eyes, you may have noticed that there is a typo in the App
component. This mistake is intentional, and we'll see later how Nx can fix this issue automatically in CI.
Visualize your Project Structure
Nx automatically detects the dependencies between the various parts of your workspace and builds a project graph. This graph is used by Nx to perform various optimizations such as determining the correct order of execution when running tasks like npx nx build
, enabling intelligent caching, and more. Interestingly, you can also visualize it.
Just run:
❯
npx nx graph
You should be able to see something similar to the following in your browser.
Let's create a git branch with the new hero component so we can open a pull request later:
❯
git checkout -b add-hero-component
❯
git add .
❯
git commit -m 'add hero component'
Testing and Linting - Running Multiple Tasks
Our current setup doesn't just come with targets for serving and building the React application, but also has targets for testing and linting. We can use the same syntax as before to run these tasks:
❯
npx nx test demo # runs the tests for demo
❯
npx nx lint ui # runs the linter on ui
More conveniently, we can also run tasks in parallel using the following syntax:
❯
npx nx run-many -t test lint
This is exactly what is configured in .github/workflows/ci.yml
for the CI pipeline. The run-many
command allows you to run multiple tasks across multiple projects in parallel, which is particularly useful in a monorepo setup.
There is a test failure for the demo
app due to the updated content. Don't worry about it for now, we'll fix it in a moment with the help of Nx Cloud's self-healing feature.
Local Task Cache
One thing to highlight is that Nx is able to cache the tasks you run.
Note that all of these targets are automatically cached by Nx. If you re-run a single one or all of them again, you'll see that the task completes immediately. In addition, (as can be seen in the output example below) there will be a note that a matching cache result was found and therefore the task was not run again.
~/acme❯
npx nx run-many -t test lint
1 ✔ nx run @acme/ui:lint
2 ✔ nx run @acme/ui:test
3 ✔ nx run @acme/demo:lint
4 ✖ nx run @acme/demo:test
5
6—————————————————————————————————————————————————————————————————————————————————————————————————————————
7
8 NX Ran targets test, lint for 2 projects (1s)
9
10 ✔ 3/4 succeeded [3 read from cache]
11
12 ✖ 1/4 targets failed, including the following:
13
14 - nx run @acme/demo:test
15
Again, the @acme/demo:test
task failed, but notice that the remaining three tasks were read from cache.
Not all tasks might be cacheable though. You can configure the cache
settings in the targetDefaults
property of the nx.json
file. You can also learn more about how caching works.
Self-Healing CI with Nx Cloud
In this section, we'll explore how Nx Cloud can help your pull request get to green faster with self-healing CI. Recall that our demo app has a test failure, so let's see how this can be automatically resolved.
The npx nx-cloud fix-ci
command that is already included in your GitHub Actions workflow (github/workflows/ci.yml
)is responsible for enabling self-healing CI and will automatically suggest fixes to your failing tasks.
1name: CI
2
3on:
4 push:
5 branches:
6 - main
7 pull_request:
8
9permissions:
10 actions: read
11 contents: read
12
13jobs:
14 main:
15 runs-on: ubuntu-latest
16 steps:
17 - uses: actions/checkout@v4
18 with:
19 filter: tree:0
20 fetch-depth: 0
21
22 - uses: actions/setup-node@v4
23 with:
24 node-version: 20
25 cache: 'npm'
26
27 - run: npm ci --legacy-peer-deps
28
29 - run: npx nx run-many -t lint test build
30
31 - run: npx nx-cloud fix-ci
32 if: always()
33
You will also need to install the Nx Console editor extension for VS Code, Cursor, or IntelliJ. For the complete AI setup guide, see our AI integration documentation.
Install Nx Console for VSCodeThe official VSCode extension for Nx.
Install Nx Console for JetBrainsAvailable for WebStorm, IntelliJ IDEA Ultimate and more!
Now, let's push the add-hero-component
branch to GitHub and open a new pull request.
❯
git push origin add-hero-component
❯
# Don't forget to open a pull request on GitHub
As expected, the CI check fails because of the test failure in the demo
app. But rather than looking at the pull request, Nx Console notifies you that the run has completed, and that it has a suggested fix for the failing test. This means that you don't have to waste time babysitting your PRs, and the fix can be applied directly from your editor.
Fix CI from Your Editor
From the Nx Console notification, you can click Show Suggested Fix
button. Review the suggested fix, which in this case is to change the typo Welcmoe
to the correct Welcome
spelling. Approve this fix by clicking ApplyFix
and that's it!
You didn't have to leave your editor or do any manual work to fix it. This is the power of self-healing CI with Nx Cloud.
Remote Cache for Faster Time To Green
After the fix has been applied and committed, CI will re-run automatically, and you will be notified of the results in your editor.
When you click View Results
to show the run in Nx Cloud, you'll notice something interesting. The lint and test tasks for the ui
library were read from remote cache and did not have to run again, thus each taking less than a second to complete.
This happens because Nx Cloud caches the results of tasks and reuses them across different CI runs. As long as the inputs for each task have not changed (e.g. source code), then their results can be replayed from Nx Cloud's Remote Cache. In this case, since the last fix was applied only to the demo
app's source code, none of the tasks for ui
library had to be run again.
This significantly speeds up the time to green for your pull requests, because subsequent changes to them have a good chance to replay tasks from cache.
Outputs from cached tasks, such as the dist
folder for builds or coverage
folder for tests, are also read from cache. Even though a task was not run again, its outputs are available. The Cache Task Results page provides more details on caching.
This pull request is now ready to be merged with the help of Nx Cloud's self-healing CI and remote caching.
Next Steps
Here are some things you can dive into next:
- Learn more about the underlying mental model of Nx
- Learn how to migrate your existing project to Nx
- Setup Storybook for our shared UI library
- Learn how to setup Tailwind
- Learn about enforcing boundaries between projects
Also, make sure you
- ⭐️ Star us on GitHub to show your support and stay updated on new releases!
- Join the Official Nx Discord Server to ask questions and find out the latest news about Nx.
- Follow Nx on Twitter to stay up to date with Nx news
- Read our Nx blog
- Subscribe to our Youtube channel for demos and Nx insights