This tutorial walks you through creating a TypeScript monorepo with Nx. You'll build a small example project to understand the core concepts and workflows.
What you'll learn:
Prerequisites
This tutorial requires a GitHub account to demonstrate the full value of Nx - including task running, caching, and CI integration.
Step 1: Creating a new Nx TypeScript workspaceLet's create your workspace. The setup process takes about 2 minutes and will configure TypeScript, testing, and CI/CD automatically.
Step 2: Verify Your SetupPlease verify closely that you have the following setup:
.github/workflows/ci.yml
pipeline preconfiguredYou 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.
This is important for using remote caching and self-healing in CI later in the tutorial.
Let's take a look at the structure of our new Nx workspace:
acme ├─ .github │ └─ workflows │ └─ ci.yml ├─ .nx │ └─ ... ├─ packages │ └─ .gitkeep ├─ README.md ├─ .prettierignore ├─ .prettierrc ├─ nx.json ├─ package-lock.json ├─ package.json ├─ tsconfig.base.json └─ tsconfig.json
Here are some files that might jump to your eyes:
.nx
folder is where Nx stores local metadata about your workspaces using the Nx Daemon.nx.json
file contains configuration settings for Nx itself and global default settings that individual projects inherit..github/workflows/ci.yml
file preconfigures your CI in GitHub Actions to run build and test through Nx.Now, let's build some features and see how Nx helps get us to production faster.
Let's create two TypeScript packages that demonstrate how to structure a TypeScript monorepo. We'll create an animal
package and a zoo
package where zoo
depends on animal
.
First, generate the animal
package:
❯
npx nx g @nx/js:lib packages/animal --bundler=tsc --unitTestRunner=vitest --linter=none
Then generate the zoo
package:
❯
npx nx g @nx/js:lib packages/zoo --bundler=tsc --unitTestRunner=vitest --linter=none
Running these commands should lead to new directories and files in your workspace:
acme ├── packages │ ├── animal │ └── zoo ├── ... └── vitest.workspace.ts
Let's add some code to our packages. First, add the following code to the animal
package:
packages/animal/src/lib/animal.ts
export function animal(): string { return 'animal'; } export interface Animal { name: string; sound: string; } const animals: Animal[] = [ { name: 'cow', sound: 'moo' }, { name: 'dog', sound: 'woof' }, { name: 'pig', sound: 'oink' }, ]; export function getRandomAnimal(): Animal { return animals[Math.floor(Math.random() * animals.length)]; }
Now let's update the zoo
package to use the animal
package:
packages/zoo/src/lib/zoo.ts
import { getRandomAnimal } from '@acme/animal'; export function zoo(): string { const result = getRandomAnimal(); return `${result.name} says ${result.sound}!`; }
Also create an executable entry point for the zoo package:
packages/zoo/src/index.ts
import { zoo } from './lib/zoo.js'; console.log(zoo());
To build your packages, run:
This creates a compiled version of your package in the dist/packages/animal
folder. Since the zoo
package depends on animal
, building zoo
will automatically build animal
first:
You'll see both packages are built, with outputs in their respective dist
folders. This is how you would prepare packages for use internally or for publishing to a package registry like NPM.
You can also run the zoo
package to see it in action:
❯
node packages/zoo/dist/index.js
Nx uses the following syntax to run tasks:
Inferred TasksBy default Nx simply runs your package.json
scripts. However, you can also adopt Nx technology plugins that help abstract away some of the lower-level config and have Nx manage that. One such thing is to automatically identify tasks that can be run for your project from tooling configuration files such as package.json
scripts and TypeScript configuration.
In nx.json
there's already the @nx/js
plugin registered which automatically identifies typecheck
and build
targets.
nx.json
{ ... "plugins": [ { "plugin": "@nx/js/typescript", "options": { "typecheck": { "targetName": "typecheck" }, "build": { "targetName": "build", "configName": "tsconfig.lib.json", "buildDepsName": "build-deps", "watchDepsName": "watch-deps" } } } ] }
To view the tasks that Nx has detected, look in the Nx Console project detail view or run:
❯
npx nx show project animal
Project Details View (Simplified)
Root: packages/animal
Type:library
Targetstsc --build tsconfig.lib.json
Cacheable
tsc --build --emitDeclarationOnly
Cacheable
The @nx/js
plugin automatically configures both the build and typecheck tasks based on your TypeScript configuration. Notice also how the outputs are set to {projectRoot}/dist
- this is where your compiled TypeScript files will be placed, and it defined by the outDir
option in packages/animal/tsconfig.lib.json
.
Overriding inferred task options
You can override the options for inferred tasks by modifying the targetDefaults
in nx.json
or setting a value in your project.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.
When you develop packages, creating shared utilities that multiple packages can use is a common pattern. This approach offers several benefits:
Let's create a shared utilities library that both our existing packages can use:
❯
npx nx g @nx/js:library packages/util --bundler=tsc --unitTestRunner=vitest --linter=none
Now we have:
acme ├── packages │ ├── animal │ ├── util │ └── zoo └── ...
Let's add a utility function that our packages can share:
packages/util/src/lib/util.ts
export function util(): string { return 'util'; } export function formatMessage(prefix: string, message: string): string { return `[${prefix}] ${message}`; } export function getRandomItem<T>(items: T[]): T { return items[Math.floor(Math.random() * items.length)]; }
This allows us to easily import them into other packages. Let's update our animals
package to use the shared utility:
packages/animals/src/lib/animals.ts
import { getRandomItem } from '@acme/util'; export function animal(): string { return 'animal'; } export interface Animal { name: string; sound: string; } const animals: Animal[] = [ { name: 'cow', sound: 'moo' }, { name: 'dog', sound: 'woof' }, { name: 'pig', sound: 'oink' }, ]; export function getRandomAnimal(): Animal { return getRandomItem(animals); }
And update the zoo
package to use the formatting utility:
packages/zoo/src/lib/zoo.ts
import { getRandomAnimal } from '@acme/animal'; import { formatMessage } from '@acme/util'; export function zoo(): string { const result = getRandomAnimal(); const message = `${result.name} says ${result.sound}!`; return formatMessage('ZOO', message); }
Now when you run npx nx build zoo
, Nx will automatically build all the dependencies in the correct order: first util
, then animal
, and finally zoo
.
Run the zoo
package to see the updated output format:
❯
node packages/zoo/dist/index.js
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:
You should be able to see something similar to the following in your browser.
Let's create a git branch with our new packages so we can open a pull request later:
❯
git checkout -b add-zoo-packages
❯
git commit -m 'add animal and zoo packages'
Our packages come with preconfigured building and testing . Let's intentionally introduce a typo in our test to demonstrate the self-healing CI feature later.
You can run tests for individual packages:
Or run multiple tasks in parallel across all packages:
❯
npx nx run-many -t build test
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 zoo
package due to the updated message. Don't worry about it for now, we'll fix it in a moment with the help of Nx Cloud's self-healing feature.
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, 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 built test
✔ nx run @acme/util:build ✔ nx run @acme/util:test ✔ nx run @acme/animal:test ✔ nx run @acme/animal:build ✖ nx run @acme/zoo:test ✔ nx run @acme/zoo:build —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— NX Ran targets test, build for 3 projects (800ms) ✔ 5/6 succeeded [5 read from cache] ✖ 1/6 targets failed, including the following: - nx run @acme/zoo:test
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.
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 zoo package has a test with a typo, 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.
.github/workflows/ci.yml
name: CI on: push: branches: - main pull_request: permissions: actions: read contents: read jobs: main: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: filter: tree:0 fetch-depth: 0 - uses: actions/setup-node@v4 with: node-version: 20 cache: 'npm' - run: npm ci --legacy-peer-deps - run: npx nx run-many -t lint test build - run: npx nx-cloud fix-ci if: always()
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.
Now, let's push the add-zoo-packages
branch to GitHub and open a new pull request.
❯
git push origin add-zoo-packages
❯
# Don't forget to open a pull request on GitHub
As expected, the CI check may show failures or issues. But rather than looking at the pull request, Nx Console notifies you that the run has completed, and if there are any issues, it may have suggested fixes. This means that you don't have to waste time babysitting your PRs, and fixes can be applied directly from your editor.
Fix CI from Your EditorFrom the Nx Console notification, if there's a suggested fix (such as fixing the typo "formated" to "formatted"), you can click Show Suggested Fix
button. Review the suggested fix and approve it by clicking Apply Fix
.
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 GreenAfter 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 tasks for packages that weren't affected by your change 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.
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.
Remote Cache Outputs
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.
The next section deals with publishing packages to a registry like NPM, but if you are not interested in publishing your packages, you can skip to the end.
If you decide to publish your packages to NPM, Nx can help you manage the release process. Release management involves updating the version of your packages, populating a changelog, and publishing the new version to the NPM registry.
First you'll need to define which projects Nx should manage releases for by setting the release.projects
property in nx.json
:
nx.json
{ ... "release": { "projects": ["packages/*"] } }
You'll also need to ensure that each package's package.json
file sets "private": false
so that Nx can publish them. If you have any packages that you do not want to publish, make sure to set "private": true
in their package.json
.
Now you're ready to use the nx release
command to publish your packages. The first time you run nx release
, you need to add the --first-release
flag so that Nx doesn't try to find the previous version to compare against. It's also recommended to use the --dry-run
flag until you're sure about the results of the nx release
command, then you can run it a final time without the --dry-run
flag.
To preview your first release, run:
❯
npx nx release --first-release --dry-run
The command will ask you a series of questions and then show you what the results would be. Once you are happy with the results, run it again without the --dry-run
flag:
❯
npx nx release --first-release
After this first release, you can remove the --first-release
flag and just run nx release --dry-run
. There is also a dedicated feature page that goes into more detail about how to use the nx release
command.
Here are some things you can dive into next:
Also, make sure you
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4