Skip to content

Commit

Permalink
docs(core): feature Nx Cloud sections more prominently in CLI tutorials
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysoo committed Jul 23, 2024
1 parent 684d2a9 commit b9a8da6
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 27 deletions.
80 changes: 55 additions & 25 deletions docs/shared/tutorials/npm-workspaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,31 @@ description: In this tutorial you'll add Nx to an existing NPM workspaces repo

# NPM Workspaces Tutorial

In this tutorial, you'll learn how to add Nx to a repository with an existing NPM workspaces setup. You'll see how Nx can provide immediate value with very little configuration and then you can gradually enable more features.
In this tutorial, you'll learn how to add Nx to a repository with an existing [NPM workspaces](https://docs.npmjs.com/cli/using-npm/workspaces) setup.

- Add Nx to the repository with a single command
- Configure caching for your existing tasks
- Configure a task pipeline
- Use Nx Plugins to automatically configure caching
What will you learn?

- how to add Nx to the repository with a single command
- how to configure caching for your tasks
- how to configure a task pipeline
- how to configure projects automatically with Nx Plugins
- how to manage your releases with `nx release`
- how to speed up CI with Nx Cloud ⚡

<!-- ## Final Source Code
Here's the source code of the final result for this tutorial.
{% github-repository url="https://github.com/nrwl/nx-recipes/tree/main/npm-workspaces" /%} -->

{% nx-cloud-section %}

## Starting Repository

To get started, check out [the sample repository](https://github.com/nrwl/tuskydesign) on your local machine:
To get started, fork [the sample repository](https://github.com/nrwl/tuskydesign/fork) and clone it on your local machine:

```shell
git clone https://github.com/nrwl/tuskydesign.git
git clone https://github.com/<your-username>/tuskydesign.git
```

The repository has two React packages (under `packages/buttons` and `packages/forms`) that are used in a `demo` application (located in `apps/demo`) that was designed to be used with the Vite CLI. The root `package.json` has a `workspaces` property that tells NPM how to find the projects in the repository.
Expand Down Expand Up @@ -63,10 +69,18 @@ When the `buttons` and `forms` projects are built first, the `demo` app can buil

Now that you have a basic understanding of the repository we're working with, let's see how Nx can help us.

## Add Nx
{% /nx-cloud-section %}

{% nx-cloud-section variant="divider" /%}

{% nx-cloud-section %}

## Smart Monorepo

Nx offers many features, but at its core, it is a task runner. Out of the box, it can cache your tasks and ensure those tasks are run in the correct order. After the initial set up, you can incrementally add on other features that would be helpful in your organization.

### Add Nx

To enable Nx in your repository, run a single command:

```shell {% path="~/tuskydesigns" %}
Expand All @@ -85,10 +99,10 @@ Second, the script asks a series of questions to help set up caching for you.
- `Which scripts are cacheable?` - Choose `typecheck`, `build` and `lint`
- `Does the "typecheck" script create any outputs?` - Enter nothing
- `Does the "build" script create any outputs?` - Enter `dist`
- `Does the "lint" script create any outputs?` - Enter nothing
- `Does the "lint" script creggggggate any outputs?` - Enter nothing
- `Would you like remote caching to make your build faster?` - Choose `Skip for now`

## Explore Your Workspace
### Explore Your Workspace

If you run `nx graph` as instructed, you'll see the dependencies between your projects.

Expand All @@ -101,7 +115,7 @@ npx nx graph --focus=@tuskdesign/demo

Nx uses this graph to determine the order tasks are run and enforce module boundaries. You can also leverage this graph to gain an accurate understanding of the architecture of your codebase. Part of what makes this graph invaluable is that it is derived directly from your codebase, so it will never become out of date.

## Caching Pre-configured
### Caching Pre-configured

Nx has been configured to run your `build`, `typecheck` and `lint` tasks. You can run a single task like this:

Expand Down Expand Up @@ -151,7 +165,7 @@ Nx read the output from the cache instead of running the command for 3 out of 3

You can see the same caching behavior working when you run `npx nx lint` or `npx nx typecheck`.

## Use Task Pipelines
### Use Task Pipelines

You may be wondering why the caching message in the previous section mentioned 3 tasks when you only ran the `build` task from the terminal. When we said that `build` tasks must be run in order during the setup script, Nx created a simple task pipeline. You can see the configuration for it in the `nx.json` file:

Expand Down Expand Up @@ -186,7 +200,7 @@ Nx read the output from the cache instead of running the command for 3 out of 3

Not only does the build complete successfully, but it finishes instantly and the `packages/forms/dist` folder is put back in place thanks to the caching.

## Create a Task Pipeline
### Create a Task Pipeline

You may have noticed in the `apps/demo/package.json` file, there is a `prebuild` script that runs `typecheck` before the `build` script in order to catch any type errors. Let's set up this same behavior in the Nx task pipeline as well.

Expand All @@ -212,7 +226,7 @@ You may have noticed in the `apps/demo/package.json` file, there is a `prebuild`

The `dependsOn` line makes Nx run the `typecheck` task for the current project and the `build` task for any dependencies before running the current project's `build` task. Now `nx build` will run the `typecheck` task just like `npm run build` does.

## Use Nx Plugins to Enhance Vite Tasks with Caching
### Use Nx Plugins to Enhance Vite Tasks with Caching

You may remember that we defined the `outputs` property in `nx.json` when we were answering questions in the `nx init` script. The value is currently hard-coded so that if you change the output path in your `vite.config.ts`, you have to remember to also change the `outputs` array in the `build` task configuration. This is where plugins can help. They directly infer information from the actual tooling configuration files (`vite.config.ts` in this case).

Expand Down Expand Up @@ -285,15 +299,21 @@ Now if you look at project details view again, you'll see that the `outputs` pro

You can also add the `@nx/eslint` plugin to see how it infers `lint` tasks based on the ESLint configuration files.

## Summary
### Summary

After following this tutorial, the repository is still using all the same tools to run tasks, but now Nx runs those tasks in a smarter way. The tasks are efficiently cached so that there is no repeated work and the cache configuration settings are automatically synced with your tooling configuration files by Nx plugins. Also, any task dependencies are automatically executed whenever needed because we configured task pipelines for the projects.
After adding Nx, the repository is still using all the same tools to run tasks, but now Nx runs those tasks in a smarter way. The tasks are efficiently cached so that there is no repeated work and the cache configuration settings are automatically synced with your tooling configuration files by Nx plugins. Also, any task dependencies are automatically executed whenever needed because we configured task pipelines for the projects.

The final task graph for `demo` app's `build` task looks like this:

{% graph height="200px" title="Build Task Pipeline" type="task" jsonFile="shared/tutorials/npm-workspaces-build-tasks2.json" %}
{% /graph %}

{% /nx-cloud-section %}

{% nx-cloud-section variant="divider" /%}

{% nx-cloud-section variant="release" %}

## Manage Releases

If you decide to publish the `forms` or `buttons` packages on NPM, Nx can also help you [manage the release process](/features/manage-releases). Release management involves updating the version of your package, populating a changelog, and publishing the new version to the NPM registry.
Expand Down Expand Up @@ -323,25 +343,33 @@ 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](/features/manage-releases) that goes into more detail about how to use the `nx release` command.
{% /nx-cloud-section %}

{% nx-cloud-section variant="divider" /%}

## Set Up CI for Your NPM Workspace
{% nx-cloud-section variant="nx-cloud" %}

This tutorial walked you through how Nx can improve the local development experience, but the biggest difference Nx makes is in CI. As repositories get bigger, making sure that the CI is fast, reliable and maintainable can get very challenging. Nx provides a solution.
## Fast CI ⚡ {% tableOfContentsColor="green" %}

{% callout type="check" title="Forked repository with Nx" %}
Make sure you have completed the previous sections of this tutorial before starting this one. If you want a clean starting point, you can fork the [sample repository with Nx already added](/).
{% /callout %}

So far in this tutorial you've seen how Nx improves the local development experience, but the biggest difference Nx makes is in CI. As repositories get bigger, making sure that the CI is fast, reliable and maintainable can get very challenging. Nx provides a solution.

- Nx reduces wasted time in CI with the [`affected` command](/ci/features/affected).
- Nx Replay's [remote caching](/ci/features/remote-cache) will reuse task artifacts from different CI executions making sure you will never run the same computation twice.
- Nx Agents [efficiently distribute tasks across machines](/ci/concepts/parallelization-distribution) ensuring constant CI time regardless of the repository size. The right number of machines is allocated for each PR to ensure good performance without wasting compute.
- Nx Agents [efficiently distribute tasks across machines](/ci/features/distribute-task-execution) ensuring constant CI time regardless of the repository size. The right number of machines is allocated for each PR to ensure good performance without wasting compute.
- Nx Atomizer [automatically splits](/ci/features/split-e2e-tasks) large e2e tests to distribute them across machines. Nx can also automatically [identify and rerun flaky e2e tests](/ci/features/flaky-tasks).

### Connect to Nx Cloud
### Connect to Nx Cloud {% tableOfContentsColor="green" %}

Nx Cloud is a companion app for your CI system that provides remote caching, task distribution, e2e tests deflaking, better DX and more.

Now that we're working on the CI pipeline, it is important for your changes to be pushed to a GitHub repository.

1. Commit your existing changes with `git add . && git commit -am "updates"`
2. [Create a new GitHub repository](https://github.com/new)
3. Follow GitHub's instructions to push your existing code to the repository
2. Push your changes to your forked GitHub repository with `git push`

Now connect your repository to Nx Cloud with the following command:

Expand All @@ -365,15 +393,15 @@ git pull

You should now have an `nxCloudAccessToken` property specified in the `nx.json` file.

### Create a CI Workflow
### Create a CI Workflow {% tableOfContentsColor="green" %}

Use the following command to generate a CI workflow file.

```shell
npx nx generate ci-workflow --ci=github
```

This generator creates a `.github/workflows/ci.yml` file that contains a CI pipeline that will run the `lint`, `test`, `build` and `e2e` tasks for projects that are affected by any given PR. Since we are using Nx Cloud, the pipeline will also distribute tasks across multiple machines to ensure fast and reliable CI runs.
This generator creates a `.github/workflows/ci.yml` file that contains a CI pipeline that will run the `lint`, `test`, `build` and `e2e` tasks for projects that are affected by any given PR. Since we are using Nx Cloud, the pipeline will also [distribute tasks across multiple machines](/ci/features/distribute-task-execution) to ensure fast and reliable CI runs.

The key lines in the CI pipeline are:

Expand Down Expand Up @@ -402,7 +430,7 @@ jobs:
- run: npx nx affected -t lint test build
```
### Open a Pull Request
### Open a Pull Request {% tableOfContentsColor="green" %}
Commit the changes and open a new PR on GitHub.
Expand All @@ -425,6 +453,8 @@ For more information about how Nx can improve your CI pipeline, check out one of
- [Circle CI with Nx](/ci/intro/tutorials/circle)
- [GitHub Actions with Nx](/ci/intro/tutorials/github-actions)

{% /nx-cloud-section %}

## Next Steps

Connect with the rest of the Nx community with these resources:
Expand Down
13 changes: 11 additions & 2 deletions nx-dev/feature-doc-viewer/src/lib/table-of-contents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ interface Heading {
id: string;
level: number;
title: string;
tableOfContentsColor?: string;
}

export function collectHeadings(
Expand All @@ -28,8 +29,7 @@ export function collectHeadings(

if (typeof title === 'string') {
sections.push({
id: node.attributes['id'],
level: node.attributes['level'],
...node.attributes,
title,
});
}
Expand Down Expand Up @@ -73,6 +73,7 @@ export function TableOfContents({
headings.find((i) => i.level === 1)?.title || null
);

console.log({ items });
return (
<>
<nav className="toc">
Expand All @@ -90,6 +91,14 @@ export function TableOfContents({
{
'border-slate-500 bg-slate-50 dark:border-slate-700 dark:bg-slate-800/60':
activeId === item.id,
// region Nx Cloud
'border-green-200 bg-green-50 dark:border-green-200 dark:bg-green-800/40 hover:border-green-500':
item.tableOfContentsColor === 'green' &&
activeId !== item.id,
'border-green-500 bg-green-50 dark:border-green-700 dark:bg-green-800/60':
item.tableOfContentsColor === 'green' &&
activeId === item.id,
// endregion Nx C`oud
'pl-6': item.level === 3,
}
)}
Expand Down
4 changes: 4 additions & 0 deletions nx-dev/ui-markdoc/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import { StackblitzButton } from './lib/tags/stackblitz-button.component';
import { stackblitzButton } from './lib/tags/stackblitz-button.schema';
import { Graph } from './lib/tags/graph.component';
import { graph } from './lib/tags/graph.schema';
import { TutorialSection } from './lib/tags/nx-cloud-section.component';
import { nxCloudSection } from './lib/tags/nx-cloud-section.schema';
import { Iframe } from './lib/tags/iframe.component';
import { iframe } from './lib/tags/iframe.schema';
import { InstallNxConsole } from './lib/tags/install-nx-console.component';
Expand Down Expand Up @@ -83,6 +85,7 @@ export const getMarkdocCustomConfig = (
graph,
iframe,
'install-nx-console': installNxConsole,
'nx-cloud-section': nxCloudSection,
persona,
personas,
'project-details': projectDetails,
Expand Down Expand Up @@ -114,6 +117,7 @@ export const getMarkdocCustomConfig = (
Heading,
Iframe,
InstallNxConsole,
NxCloudSection: TutorialSection,
Persona,
Personas,
ProjectDetails,
Expand Down
1 change: 1 addition & 0 deletions nx-dev/ui-markdoc/src/lib/nodes/heading.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export const heading: Schema = {
id: { type: 'String' },
level: { type: 'Number', required: true, default: 1 },
className: { type: 'String' },
tableOfContentsColor: { type: 'String' },
},
transform(node, config) {
const attributes = node.transformAttributes(config);
Expand Down
24 changes: 24 additions & 0 deletions nx-dev/ui-markdoc/src/lib/tags/nx-cloud-section.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { JSX, ReactNode } from 'react';

interface TutorialSectionProps {
variant: 'generic' | 'nx-cloud' | 'divider';
children: ReactNode;
}
export function TutorialSection({ variant, children }: TutorialSectionProps) {
switch (variant) {
case 'nx-cloud':
return (
<div className="-ml-5 border-l-4 border-green-700 pl-4">{children}</div>
);
// case 'divider':
// return (
// <div className="my-12 -ml-4 flex">
// <span className="h-[6px] w-[6px] -ml-[2px] rounded-full bg-slate-400"></span>
// </div>
// );
default:
return (
<div className="">{children}</div>
);
}
}
12 changes: 12 additions & 0 deletions nx-dev/ui-markdoc/src/lib/tags/nx-cloud-section.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Schema } from '@markdoc/markdoc';

export const nxCloudSection: Schema = {
render: 'NxCloudSection',
attributes: {
variant: {
type: 'String',
matches: ['generic', 'nx-cloud', 'divider'],
default: 'generic',
},
}
};

0 comments on commit b9a8da6

Please sign in to comment.