Overview
One of the primary benefits of a monorepo is code sharing. This lesson focuses on extracting reusable UI components and utility functions into dedicated shared packages, making them accessible to all applications within the monorepo.
Key Points
-
Create
uiPackage: Set up a new package (e.g.,packages/ui) that will house common React components. This package will have its ownpackage.json,tsconfig.json, and source files. -
Create
utilsPackage: Similarly, create apackages/utilsfor reusable helper functions, hooks, or constants. -
Export Shared Assets: Within each shared package, ensure that components and functions are properly exported so they can be consumed by other workspaces.
-
Import in Next.js App: In your Next.js application, add the shared package as a dependency in its
package.json(using"workspace:*"or"workspace:^") and then import the components/utilities directly. -
Dependency Management: Use your package manager to link the local shared packages to your Next.js app. Running
pnpm install(ornpm install,yarn install) from the monorepo root handles this linking.
Quick Example
1. packages/ui/src/button.tsx:
typescript import React from 'react';
export function Button({ children }: { children: React.ReactNode }) { return <button style={{ padding: '10px 20px', borderRadius: '5px' }}>{children}</button>; }
2. apps/web/package.json (add dependency):
json{ "name": "web", "version": "1. 0. 0", "dependencies": { "@repo/ui": "workspace:*" } }
3. apps/web/app/page.tsx (import and use):
typescriptimport { Button } from "@repo/ui"; export default function HomePage() { return ( <div> <h1>Welcome!</h1> <Button>Click Me</Button> </div> ); } ## Summary By creating and utilizing shared `ui` and `utils` packages, you centralize common code, enhance consistency, and significantly improve maintainability across all applications within your Turborepo monorepo. This is a cornerstone of effective monorepo development.