React Monorepo Tutorial - Part 2: Project Graph

Run the command: npx nx graph. A browser should open up with the following contents:

Initial Project Graph

This is still different than the design from the start of Part 1:

Our Workspace Requirements

The Project Graph is derived from the source code of your workspace. Make the following adjustments to your existing projects, so that our Project Graph will match the design:

common-ui

Run the @nx/react:component generator with the command:

~/myorg

npx nx g @nx/react:component banner --project=common-ui --export

1 2> NX Generating @nx/react:component 3 4CREATE libs/common-ui/src/lib/banner/banner.module.css 5CREATE libs/common-ui/src/lib/banner/banner.spec.tsx 6CREATE libs/common-ui/src/lib/banner/banner.tsx 7UPDATE libs/common-ui/src/index.ts 8
Nx 15 and lower use @nrwl/ instead of @nx/

Then create a simple Banner component in the generated file:

libs/common-ui/src/lib/banner/banner.tsx
1export interface BannerProps { 2 text: string; 3} 4 5export function Banner(props: BannerProps) { 6 return <header>{props.text}</header>; 7} 8 9export default Banner; 10

admin

Add the Banner component to the admin app:

apps/admin/src/app/app.tsx
1import { Banner } from '@myorg/common-ui'; 2 3export function App() { 4 return ( 5 <> 6 <Banner text="Welcome to our admin app." /> 7 <div /> 8 </> 9 ); 10} 11 12export default App; 13

products

Export a Product TS interface and some example products:

libs/products/src/lib/products.ts
1export interface Product { 2 id: string; 3 name: string; 4 price: number; 5} 6 7export const exampleProducts: Product[] = [ 8 { 9 id: '1', 10 name: 'Product 1', 11 price: 100, 12 }, 13 { 14 id: '2', 15 name: 'Product 2', 16 price: 200, 17 }, 18]; 19

store

Use both the Banner component from your common-ui lib, and the exampleProducts from your products lib:

apps/store/src/app/app.tsx
1import { Banner } from '@myorg/common-ui'; 2import { exampleProducts } from '@myorg/products'; 3 4// eslint-disable-next-line @typescript-eslint/no-unused-vars 5export function App() { 6 return ( 7 <> 8 <Banner text="Welcome to the store!" /> 9 <ul> 10 {exampleProducts.map((product) => ( 11 <li key={product.id}> 12 <strong>{product.name}</strong> Price: {product.price} 13 </li> 14 ))} 15 </ul> 16 </> 17 ); 18} 19 20export default App; 21

Now run npx nx graph again:

Matching Graph

Our Workspace Requirements

Your graph now matches the original design.

The Project Graph is more than just a visualization - Nx provides tooling to optimize your task-running and even automate your CI based on this graph. This will be covered in more detail in: 4: Workspace Optimization.

What's Next