Building a TypeScript Library in a Monorepo with PNPM and Turborepo
/ 2 min read
📌 Introduction
Building a TypeScript library in a monorepo offers several advantages, including better code sharing, streamlined dependency management, and easier maintainability. This guide will walk you through setting up a monorepo structure for a TypeScript library using modern tools like pnpm, Turborepo, and TypeScript.
🛠️ Setting Up the Monorepo
Initialize the Monorepo
We will use pnpm as our package manager since it natively supports workspaces and provides better performance compared to npm and yarn.
mkdir ts-monorepo && cd ts-monorepopnpm initEnable workspaces in pnpm by adding the following to package.json:
1{2 "private": true,3 "workspaces": ["packages/*"]4}Install Turborepo for Task Orchestration
Turborepo helps manage build processes and dependencies efficiently.
pnpm add -D turboCreate a turbo.json configuration file:
1{2 "$schema": "https://turborepo.org/schema.json",3 "pipeline": {4 "build": {5 "dependsOn": ["^build"],6 "outputs": ["dist/**"]7 },8 "lint": {},9 "test": {}10 }11}🏗️ Creating the TypeScript Library
Set Up the Package
Create a new package for the library:
mkdir -p packages/my-library && cd packages/my-librarypnpm initInstall TypeScript and necessary dependencies:
pnpm add -D typescript tsup eslint @types/nodeCreate a tsconfig.json file:
1{2 "compilerOptions": {3 "outDir": "dist",4 "module": "ESNext",5 "target": "ES6",6 "declaration": true,7 "strict": true,8 "esModuleInterop": true9 },10 "include": ["src"]11}Implement the Library Code
Inside packages/my-library, create a src folder and an index.ts file:
mkdir src && touch src/index.tsWrite a simple function inside src/index.ts:
1export function greet(name: string): string {2 return `Hello, ${name}!`;3}Build the Library
Add a build script to package.json:
1{2 "scripts": {3 "build": "tsup src/index.ts --format esm,cjs --dts"4 }5}Run the build command:
pnpm buildLink the Library in Another Package
If you want to use the library in another package within the monorepo, create another package (e.g., app) and add my-library as a dependency:
pnpm add my-library --filter appNow, you can import and use the library inside the app package.
1import { greet } from "my-library";2console.log(greet("World"));✅ Conclusion
Setting up a TypeScript library in a monorepo structure provides a scalable way to manage dependencies, reuse code, and streamline development. By leveraging pnpm, Turborepo, and TypeScript, you can build and maintain a high-performance library efficiently.
